如何在C中通过引用传递结构数组?
举个例子:
struct Coordinate {
int X;
int Y;
};
SomeMethod(Coordinate *Coordinates[]){
//Do Something with the array
}
int main(){
Coordinate Coordinates[10];
SomeMethod(&Coordinates);
}
发布于 2009-07-09 23:35:22
在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:
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
您可以在声明类型时对其进行类型定义(这是C中的一种常见习惯用法):
typedef struct Coordinate {
int x;
int y;
} Coordinate;
发布于 2009-07-10 15:23:32
在这里稍微扩展一下一些答案……
在C中,当一个数组标识符出现在一个上下文中,而不是作为操作数出现在&或sizeof时,标识符的类型被隐式地从“T的N元素数组”转换为“指向T的指针”,并且它的值被隐式地设置为数组中第一个元素的地址(与数组本身的地址相同)。这就是为什么当您只是将数组标识符作为参数传递给函数时,函数会接收指向基类型的指针,而不是数组。由于您不能仅通过查看指向第一个元素的指针来判断数组的大小,因此必须将大小作为单独的参数传入。
struct Coordinate { int x; int y; };
void SomeMethod(struct Coordinate *coordinates, size_t numCoordinates)
{
...
coordinates[i].x = ...;
coordinates[i].y = ...;
...
}
int main (void)
{
struct Coordinate coordinates[10];
...
SomeMethod (coordinates, sizeof coordinates / sizeof *coordinates);
...
}
将数组传递给函数有两种替代方法。
有这样一种东西,即指向T数组的指针,而不是指向T的指针。
T (*p)[N];
在这种情况下,p是指向T N元素数组的指针(与T *pN相反,其中p是指向T的N元素数组)。因此,您可以传递指向数组的指针,而不是指向第一个元素的指针:
struct Coordinate { int x; int y };
void SomeMethod(struct Coordinate (*coordinates)[10])
{
...
(*coordinates)[i].x = ...;
(*coordinates)[i].y = ...;
...
}
int main(void)
{
struct Coordinate coordinates[10];
...
SomeMethod(&coordinates);
...
}
这种方法的缺点是数组大小是固定的,因为指向T的10元素数组的指针与指向T的20元素数组的指针的类型不同。
第三种方法是将数组包装在结构中:
struct Coordinate { int x; int y; };
struct CoordinateWrapper { struct Coordinate coordinates[10]; };
void SomeMethod(struct CoordinateWrapper wrapper)
{
...
wrapper.coordinates[i].x = ...;
wrapper.coordinates[i].y = ...;
...
}
int main(void)
{
struct CoordinateWrapper wrapper;
...
SomeMethod(wrapper);
...
}
这种方法的优点是你不会浪费在指针上。缺点是数组大小是固定的(同样,10个元素的T数组与20个元素的T数组的类型不同)。
发布于 2009-07-09 23:29:33
C语言不支持任何类型的按引用传递。最接近的等效方法是传递一个指向该类型的指针。
下面是两种语言的人工制作的示例
C++风格接口
void UpdateValue(int& i) {
i = 42;
}
最接近的C等价物
void UpdateValue(int *i) {
*i = 42;
}
https://stackoverflow.com/questions/1106957
复制相似问题