如何在 C 中通过引用传递结构数组?
举个例子:
struct Coordinate {
int X;
int Y;
};
SomeMethod(Coordinate *Coordinates[]){
//Do Something with the array
}
int main(){
Coordinate Coordinates[10];
SomeMethod(&Coordinates);
}
最佳答案
在 C 中,数组作为指向第一个元素的指针传递。它们是唯一没有真正按值传递的元素(指针按值传递,但不复制数组)。这允许被调用的函数修改内容。
void reset( int *array, int size) {
memset(array,0,size * sizeof(*array));
}
int main()
{
int array[10];
reset( array, 10 ); // sets all elements to 0
}
现在,如果您想要更改数组本身(元素的数量...),您不能使用堆栈或全局数组来完成,只能使用堆中动态分配的内存。在这种情况下,如果你想改变指针,你必须传递一个指向它的指针:
void resize( int **p, int size ) {
free( *p );
*p = malloc( size * sizeof(int) );
}
int main() {
int *p = malloc( 10 * sizeof(int) );
resize( &p, 20 );
}
在问题编辑中,您专门询问了有关传递结构数组的问题。您有两个解决方案:声明一个 typedef,或者明确表示您正在传递一个结构:
struct Coordinate {
int x;
int y;
};
void f( struct Coordinate coordinates[], int size );
typedef struct Coordinate Coordinate; // generate a type alias 'Coordinate' that is equivalent to struct Coordinate
void g( Coordinate coordinates[], int size ); // uses typedef'ed Coordinate
您可以在声明类型时对类型进行 typedef(这是 C 语言中的常用习惯用法):
typedef struct Coordinate {
int x;
int y;
} Coordinate;
关于c - 在 C 中通过引用传递数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1106957/