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

代码释放的结构看起来类似的-不要忘了打电话给免费的()上的一切你了通过malloc分配的内存!(此外,在强大的应用程序的,你应该 检查返回的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.

其他提示

传递一个明确的指针指向的第一个元件阵列方面作为单独的参数。例如,为了处理意大2-d列int:

void func_2d(int *p, size_t M, size_t N)
{
  size_t i, j;
  ...
  p[i*N+j] = ...;
}

这将是被称为

...
int arr1[10][20];
int arr2[5][80];
...
func_2d(&arr1[0][0], 10, 20);
func_2d(&arr2[0][0], 5, 80);

同样的原则也适用于较高的层面阵列:

func_3d(int *p, size_t X, size_t Y, size_t Z)
{
  size_t i, j, k;
  ...
  p[i*Y*Z+j*Z+k] = ...;
  ...
}
...
arr2[10][20][30];
...
func_3d(&arr[0][0][0], 10, 20, 30);

你可以宣布你能为:

f(int size, int data[][size]) {...}

编译器将然后做所有的指针算你。

注意,尺寸大小必须出现 之前 阵列本身。

GNU C允许参数声明的转发(在情况你真正需要通过维之后array):

f(int size; int data[][size], int size) {...}

第一个层面,虽然可以通过尽的论点也是无用的,C编译器(甚至对于sizeof操作,当应用于列作为传递的论点将始终享是作为一个指向的第一个元素)。

int matmax(int **p, int dim) // p- matrix , dim- dimension of the matrix 
{
    return p[0][0];  
}

int main()
{
   int *u[5]; // will be a 5x5 matrix

   for(int i = 0; i < 5; i++)
       u[i] = new int[5];

   u[0][0] = 1; // initialize u[0][0] - not mandatory

   // put data in u[][]

   printf("%d", matmax(u, 0)); //call to function
   getche(); // just to see the result
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top