如何在C中通过引用传递一组结构?
举个例子:
struct Coordinate {
int X;
int Y;
};
SomeMethod(Coordinate *Coordinates[]){
//Do Something with the array
}
int main(){
Coordinate Coordinates[10];
SomeMethod(&Coordinates);
}
Run Code Online (Sandbox Code Playgroud) 这个问题的目的是提供一个关于如何在C中动态正确分配多维数组的参考.这是一个经常被误解的主题,即使在一些C编程书籍中也很难解释.因此,即使是经验丰富的C程序员也很难做到正确.
我从编程教师/书籍/教程中了解到,动态分配多维数组的正确方法是使用指针指针.
然而,SO上的几个高代表用户现在告诉我这是错误和不好的做法.他们说指针到指针不是数组,我实际上并没有分配数组,而且我的代码不必要地慢.
这就是我教我分配多维数组的方法:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
int** arr_alloc (size_t x, size_t y)
{
int** pp = malloc(sizeof(*pp) * x);
assert(pp != NULL);
for(size_t i=0; i<x; i++)
{
pp[i] = malloc(sizeof(**pp) * y);
assert(pp[i] != NULL);
}
return pp;
}
int** arr_fill (int** pp, size_t x, size_t y)
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
pp[i][j] = (int)j + 1;
}
}
return pp;
}
void arr_print (int** pp, size_t x, size_t y) …Run Code Online (Sandbox Code Playgroud) c arrays dynamic-arrays dynamic-allocation variable-length-array
在 C 中,我知道我们可以用指针来做到这一点:
int *p; /* an int pointer (ptr to an int) */
int **pp; /* a pointer to an int pointer (ptr to a ptr to an int) */
Run Code Online (Sandbox Code Playgroud)
乃至:
int **app[]; /* an array of pointers to int pointers */
int (**ppa)[]; /* a pointer to a pointer to an array of ints */
int (**ppf)(); /* a pointer to a pointer to a function returning an int */
int *(*pap)[]; /* a pointer to an array …Run Code Online (Sandbox Code Playgroud)