简体   繁体   English

结构C中的未声明变量

[英]Undeclared Variable in struct C

My struct code is just like this: 我的结构代码是这样的:

typedef struct  
{  
    int w;  
    int h;  
    float m[w][h];  
} Matrix;

But I'm just getting this errors: 但我只是得到这个错误:
"error: 'w' undeclared here (not in a function)" “错误:此处未声明'w'(不在函数中)”
"error: 'h' undeclared here (not in a function)" “错误:此处未声明'h'(不在函数中)”

How can I have this struct correctly coded? 我该如何正确编码此结构?

The answer from Muli shows how to resolve your problem. Muli的答案显示了如何解决您的问题。 Here is the explanation of the compilation failure: the compiler does not know where are the boundaries of how much memory to allocate for each Matrix struct declaration because the dimensions (the values of w and h) are not known at compile time. 这是编译失败的解释:编译器不知道为每个Matrix结构声明分配多少内存的边界在哪里,因为在编译时不知道维数(w和h的值)。 If the max dimensions of the m array are known at build time, you can use a predefined size struct, like 如果在构建时知道m数组的最大尺寸,则可以使用预定义的大小结构,例如

#define MAX_W 10
#define MAX_H 10

struct {
   int w;  
   int h;  
   float m[MAX_W][MAX_H];  
};

struct matrix my_matrix;
...

afterwards you can declare and use matrix structs as you want. 之后,您可以根据需要声明和使用矩阵结构。 The drawback of this approach is the cost of allocating more memory than necessary. 这种方法的缺点是分配比必要更多的内存的成本。

Following the linux kernel coding gudelines, I don't fancy typedefs because they tend to make the data definitions opaque: if something is declared elsewhere as the typedefined type, understanding that is a struct is somewhat more complicated. 遵循linux内核编码规范,我不喜欢typedef,因为它们会使数据定义变得不透明:如果在其他地方将某些内容声明为类型定义类型,则理解结构是有点复杂的事情。

Your code will not compile. 您的代码将无法编译。 C is different from Java and high-level languages. C与Java和高级语言不同。

typedef struct  
{  
    int w;  
    int h;  
    float **elements;  
} Matrix;


Matrix* initializeMatrix(int w,int h){

 Matrix * matrix;
 int i,j;
 if( NULL == (matrix = malloc(sizeof(Matrix))) ) {
   printf("malloc failed\n");
   return NULL;
 }

 matrix.w=w;
 matrix.h=h;

 if( NULL == (matrix->elements = malloc(w * sizeof(float*))) ) {
   printf("malloc failed\n");
   free(matrix);
   return NULL;
  }

 for(i = 0; i< matrix.w ; i++){
  if( NULL == (matrix->elements[i] = malloc(h * sizeof(float))) ) {
   printf("malloc failed\n");
   for(j = i ; j>=0 ; j--)
    free(matrix->elements[j]);
   free(matrix);
   return NULL;
  }
 }

 return matrix;
}

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

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