简体   繁体   English

C函数中的多维数组

[英]Multidimensional arrays in functions in c

I have this exercise to make a transpose of a matrix in C. I made a function to check for type n*n but when I'm trying to ask the user for the matrix I don't know how I should declare the array. 我进行了此练习,以在C中转置矩阵。我制作了一个函数来检查类型n * n,但是当我尝试向用户询问矩阵时,我不知道该如何声明该数组。 And I'm getting this compile error "type of formal parameter 1 is incomplete" in the function on the [n2] part. 我在[n2]部分的函数中收到此编译错误“形式参数1的类型不完整”。

The parameters of the functions for multi dimensional arrays shouldn't be like this -> int matrix[][n2]. 多维数组的函数参数不应该像这样-> int matrix [] [n2]。 or is cause i'm using a variable and not a constant or a pre defined size. 或者是因为我使用的是变量而不是常量或预定义的大小。 ?

#include <stdio.h>
#define prompt "Dimenção da matriz (nxn) >>"
#define prompt_1 "Introduza os valores : "

void getType( int *n1, int *n2 );
void getMatrix( int matrix[][n2], int lim1, int lim2);
//void trans(int matrix[][n2]);

int main(int argc, char const *argv[]) {
  int n1, n2;
  getType(&n1, &n2);
  int matrix[n1][n2];
  //printf("%dx%d\n", n1, n2);
  getMatrix(matrix, n1, n2);
  //trans(matrix);
  return 0;
}

void getType(int *n1, int *n2){
  printf("%s", prompt );
  scanf("%dx%d", &(*n1), &(*n2));
}

void getMatrix( int matrix[][n2], int lim1, int lim2){
  printf("%s\n", prompt_1 );
  for(int line  = 0; line < lim1; line++ ){
    for(int column = 0; column < lim2; column++){
      printf("Linha %d coluna %d ->", line, column );
      scanf("%d", &matrix[line][column]);
    }
  }
}

The signature should be: 签名应为:

void getMatrix( int lim1, int lim2, int matrix[lim1][lim2] )

You are allowed omit the lim1 inside square brackets but it is good documentation to include it. 您可以省略方括号内的lim1,但包括它是一个很好的文档。

The main point is that the variable inside the square brackets must either be a parameter from earlier in the parameter list, or some other variable in scope (which can only be a global variable, but that's usually a bad idea). 要点是,方括号内的变量必须是参数列表中较早版本的参数,或者是范围内的其他变量(只能是全局变量,但这通常是个坏主意)。

Also it would be good to check scanf return value otherwise you may create matrix with garbage dimension. 另外,检查scanf返回值也将是一件好事,否则您可能会创建具有垃圾尺寸的矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM