Brian Hardy
Brian Hardy

Reputation: 29

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)"
"error: 'h' undeclared here (not in a function)"

How can I have this struct correctly coded?

Upvotes: 1

Views: 1859

Answers (2)

AdRiX
AdRiX

Reputation: 79

The answer from Muli shows how to resolve your problem. 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. If the max dimensions of the m array are known at build time, you can use a predefined size struct, like

#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.

Upvotes: 1

Muli Yulzary
Muli Yulzary

Reputation: 2569

Your code will not compile. C is different from Java and high-level languages.

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;
}

Upvotes: 0

Related Questions