c语言字符串数组做函数参数传递,在C中传递多维数组作为函数参数

您可以使用任何数据类型。只需使其成为指针指针:

typedef struct {

int myint;

char* mystring;

} data;

data** array;

但不要忘记,你仍然有malloc的变量,它的确有点复杂:

//initialize

int x,y,w,h;

w = 10; //width of array

h = 20; //height of array

//malloc the 'y' dimension

array = malloc(sizeof(data*) * h);

//iterate over 'y' dimension

for(y=0;y

//malloc the 'x' dimension

array[y] = malloc(sizeof(data) * w);

//iterate over the 'x' dimension

for(x=0;x

//malloc the string in the data structure

array[y][x].mystring = malloc(50); //50 chars

//initialize

array[y][x].myint = 6;

strcpy(array[y][x].mystring, "w00t");

}

}

解除分配结构的代码看起来类似 – 不要忘记调用free()对你的错误! (此外,在健壮的应用程序,你应该check the return of malloc().)

现在,让我们说,你想传递给一个函数。你仍然可以使用双指针,因为你可能想对数据结构进行操作,而不是数据结构指针的指针:

int whatsMyInt(data** arrayPtr, int x, int y){

return arrayPtr[y][x].myint;

}

调用此函数:

printf("My int is %d.\n", whatsMyInt(array, 2, 4));

输出:

My int is 6.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值