按引用传递C中的数组? [英] Passing an array by reference in C?

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

问题描述

我如何才能通过引用C中传递结构的数组?

作为一个例子:

 结构协调中心{
   INT X;
   INTÿ;
};
的someMethod(坐标*坐标[]){
   //做一些与阵列
}
诠释主(){
   坐标坐标[10];
   的someMethod(安培;坐标);
}


解决方案

在C数组作为指针的第一个元素传递。他们是不是真正按值传递(指针是按值传递,但数组不会被复制)的唯一元素。允许被调用的函数来修改内容。

 无效复位(INT *数组,INT大小){
   memset的(数组,0,大小* sizeof的(*数组));
}
诠释的main()
{
   int数组[10];
   复位(阵列,10); //设置为0的所有元素
}

现在,如果你想要的是改变了数组本身(元素个数......),你不能用堆栈或全局数组做到这一点,只有在堆中动态分配的内存。在这种情况下,如果你想改变指针,你必须通过它的指针:

 无效调整大小(INT ** P,诠释大小){
   免费的(* P);
   * P =(INT *)malloc的(大小*的sizeof(INT));
}
诠释主(){
   为int * p =(INT *)malloc的(10 * sizeof的(INT));
   调整大小(安培; P,20);
}

在这个问题编辑您专门询问传递结构的数组。你有两个解决方案有:声明一个typedef,或作出明确要传递一个结构:

 结构协调中心{
   INT X;
   诠释Ÿ;
};
无效F(结构坐标坐标[],INT大小);
typedef结构坐标坐标; //生成一个类型别名'坐标',等效于结构体坐标
无效克(坐标坐标[],INT大小); //使用Typedef的坐标

你声明它你可以的typedef类型(它是在C常见的成语):

  typedef结构协调中心{
   INT X;
   诠释Ÿ;
}协调;

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

As an example:

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

解决方案

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 = (int*) malloc( size * sizeof(int) );
}
int main() {
   int *p = (int*) malloc( 10 * sizeof(int) );
   resize( &p, 20 );
}

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

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天全站免登陆