函数内二维数组的动态分配(使用指针返回分配对象的地址)
我想知道如何使用函数参数将指针传递给动态分配的数组。该函数应该分配数组 10x10(为了简单起见,跳过了检查)。这可能吗?我做错了什么?提前致谢。
int array_allocate2DArray ( int **array, unsigned int size_x, unsigned int size_y)
{
array = malloc (size_x * sizeof(int *));
for (int i = 0; i < size_x; i++)
array[i] = malloc(size_y * sizeof(int));
return 0;
}
int main()
{
int **array;
array_allocate2DArray (*&array, 10, 10);
}
I'd /ike to know, how to pass pointers to dynamically allocated arrays using function arguments. This function is supposed to allocate array 10x10 (checks skipped for simplicity sake). Is this possible? What am i doing wrong? Thanks in advance.
int array_allocate2DArray ( int **array, unsigned int size_x, unsigned int size_y)
{
array = malloc (size_x * sizeof(int *));
for (int i = 0; i < size_x; i++)
array[i] = malloc(size_y * sizeof(int));
return 0;
}
int main()
{
int **array;
array_allocate2DArray (*&array, 10, 10);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我面临类似的问题时,我遇到了这篇文章(我正在寻找一种在 C 中动态分配字符串数组的方法)。我更喜欢从函数返回数组指针。以下内容对我有用(我根据您的整数数组对其进行了调整)。我为每个值任意设置 99,这样我就可以在 main.c 中看到它们打印出来。
I came across this post when I was facing a similar problem (I was looking for a way to dynamically allocate an array of strings in C). I prefer to return the array pointer from the function. The following worked for me (I adapted it for your array of integers). I arbitrarily set 99 for each value so I could see them printed out in main.
尝试这样的操作:
我使用临时
p
来避免混淆。Try something like this:
I used the temporary
p
to avoid confusion.