在C中通过引用传递数组? [英] Passing an array by reference in C?

查看:28
本文介绍了在C中通过引用传递数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中通过引用传递结构数组?

How can I pass an array of structs by reference in C?

举个例子:

struct Coordinate {
   int X;
   int Y;
};
SomeMethod(Coordinate *Coordinates[]){
   //Do Something with the array
}
int main(){ 
   Coordinate Coordinates[10];
   SomeMethod(&Coordinates);
}

推荐答案

在 C 中,数组作为指向第一个元素的指针传递.它们是唯一没有真正按值传递的元素(指针按值传递,但不复制数组).这允许被调用的函数修改内容.

In C arrays are passed as a pointer to the first element. They are the only element that is not really passed by value (the pointer is passed by value, but the array is not copied). That allows the called function to modify the contents.

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
}

现在,如果您想要更改数组本身(元素数量...),则不能使用堆栈或全局数组来实现,只能使用堆中动态分配的内存.在这种情况下,如果你想改变指针,你必须传递一个指针给它:

Now, if what you want is changing the array itself (number of elements...) you cannot do it with stack or global arrays, only with dynamically allocated memory in the heap. In that case, if you want to change the pointer you must pass a pointer to it:

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,或者明确你正在传递一个结构:

In the question edit you ask specifically about passing an array of structs. You have two solutions there: declare a typedef, or make explicit that you are passing an 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

您可以在声明类型时对其进行 typedef(这是 C 中的常见习语):

You can typedef the type as you declare it (and it is a common idiom in C):

typedef struct Coordinate {
   int x;
   int y;
} Coordinate;

这篇关于在C中通过引用传递数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆