在 C 中将多维数组作为函数参数传递 [英] Passing multidimensional arrays as function arguments in C

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

问题描述

C 中,当我不知道多维数组的维数时,我是否可以将多维数组作为单个参数传递给函数?数组将是?

In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be?

此外,我的多维数组可能包含字符串以外的类型.

Besides, my multidimensional array may contain types other than strings.

推荐答案

您可以使用任何数据类型执行此操作.只需将其设为指针:

You can do this with any data type. Simply make it a pointer-to-pointer:

typedef struct {
  int myint;
  char* mystring;
} data;

data** array;

但是不要忘记你仍然需要 malloc 变量,它确实变得有点复杂:

But don't forget you still have to malloc the variable, and it does get a bit complex:

//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<h;y++){
  //malloc the 'x' dimension
  array[y] = malloc(sizeof(data) * w);

  //iterate over the 'x' dimension
  for(x=0;x<w;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()!(此外,在强大的应用程序中,您应该检查 malloc() 的返回.)

The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc().)

现在假设你想把它传递给一个函数.您仍然可以使用双指针,因为您可能想要对数据结构进行操作,而不是指向数据结构指针的指针:

Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:

int whatsMyInt(data** arrayPtr, int x, int y){
  return arrayPtr[y][x].myint;
}

调用这个函数:

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

输出:

My int is 6.

这篇关于在 C 中将多维数组作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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