c - 如何返回一个指向完整数组的指针,也就是 int(*)[] 到主函数

标签 c pointers memory

我的函数目的是在堆上创建一个二维整数数组。在创建指向整个数组的指针后,我将指向整个数组的指针返回给 void*。我觉得有更好的返回类型,但我似乎无法获得写入语法。

如果我可以做一个更好的返回类型而不仅仅是 void*,请告诉我。

void* create_matrix(int x, int y){
    int i, j, count;
    int(*matrix)[x] = calloc(y, sizeof *matrix); // a pointer to a full array of size x.
    //matrix = address of array
    //*matrix = address of first element of array; *(matrix + 1) = address of first element of second array
    //**matrix = element that exists at the first element of array; *(*(matrix + 1) + 1) = second element of second array = matrix[1][1]
    count = 0;
    for(i = 0; i < y; i++){
        for(j = 0; j < x; j++){
            matrix[i][j] = ++count;
        }
    }
    for(i = 0; i < y; i++){
        for(j = 0; j < x; j++){
            printf("%d\n", matrix[i][j]);
        }
    }
    return matrix;
}

最佳答案

您可以返回一个指向未指定大小的数组的指针:

int (*create_matrix(int x, int y))[]
{
   ...
}

这将与指向 VLA 的指针兼容:

int (*a)[x]=create_matrix(x,y);

数组类型是兼容的,因为大小在两个地方都不是常量。这在 C standard 的第 6.7.6.2p6 节中指定。 :

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values

关于c - 如何返回一个指向完整数组的指针,也就是 int(*)[] 到主函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73326880/

相关文章:

C++ Overload Operator = for Pointers 不能正常工作/编译

在linux上读写物理地址内存的自定义代码

c - 动态数据结构

Perl Image::Magick 获取内存中的内容

memory - Redis 需要多少空闲内存才能运行?

c - 在 C 中,查看一个数是否可​​以被另一个数整除的最佳方法是什么?

涉及动态分配二维数组的 malloc 的 C 代码在编译后崩溃

c++ - 为什么我的客户端会杀死我的服务器?

c++ - 如何使用 FILE* 写入内存缓冲区?

c - 解决使用C的strcmp函数比较两个不同结构的元素时的警告