通过多维数组作为C函数参数 [英] Passing multidimensional arrays as function arguments in C

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

问题描述

在C I可以通过一个多维数组给一个函数,当我不知道一个参数是什么阵列的尺寸将是?

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 ?

另外我多维数组可能包含不是字符串类型。

In addition 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");
  }
}

在code解除分配结构类似于 - 不要忘了对你的一切调用malloced免费()! (另外,健壮的应用程序,你应该检查的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.\n", whatsMyInt(array, 2, 4));

输出:

My int is 6.

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

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