【问题标题】:how can i return an array from a function如何从函数返回数组
【发布时间】:2022-10-01 01:52:57
【问题描述】:

如何从函数返回数组,我正在尝试使用此转换函数执行(3*3)*(3*1) 矩阵乘法,以及如何从中获取数组。

#include <stdio.h>
#include <math.h>

int* translation(int x, int y, int tx, int ty) {
    static int res[3][1] = {0}, xy[3][1] = {{x},{y},{1}};
    int tm[3][3] = {{1,0, tx}, {0,1,ty}, {0,0,1}};
    for (int i = 0; i<3; i++) {
        for (int j = 0; j<3; j++) {
            res[i][0] += tm[i][j]*xy[j][0];
        }
    }
    return res;
}

int main()
{
    int *arr[3][1];
    arr = translation(5, 5);
    printf(\"%d %d %d\", arr[0][0], arr[0][1], arr[0][2]);
    return 0;
}
  • 您将其打包在struct 中 - 没有其他方法可以“返回数组”。你可以返回一个struct { int*; size_t len; } 然后调用者就会知道......

标签: c


【解决方案1】:

“如何从函数返回数组”

你不能。

语言没有这样的概念。

您必须返回包括长度在内的内容,以便为函数的用户提供信息。在 C 中,惯用的方法是提供一个指向函数的指针并获得一个值(通过该指针)作为回报:

size_t no_idea;
void function(void *data, &no_idea);

作为此功能的用户,您必须在判断之前阅读no_idea

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 2012-06-17
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多