1

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?

OmG
  • 18,337
  • 10
  • 57
  • 90
  • 6
    You can't have variable-length arrays inside a struct definition. You will - unfortunately - need to use pointers instead. (Something along the lines of `float *m;` then `Matrix foo; foo.m = malloc(foo.w * foo.h * sizeof foo.m[0]);`) – The Paramagnetic Croissant Oct 05 '14 at 18:35
  • Each data type in C has a fixed byte length, which is known before compilation (Integer - 4 bytes, Double - 8 bytes etc). You can not have a data type Matrix, which has a variable length. – Ivan Kuckir Oct 05 '14 at 19:24

2 Answers2

1

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.

AdRiX
  • 69
  • 1
  • 1
  • 8
0

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;
}
Muli Yulzary
  • 2,559
  • 3
  • 21
  • 39