-1

I have been writing a terminal application in C and i've been having a weird issue with structs. When I try and compile I get the error "error: initializer element is not constant". Any help is greatly appreciated.

This is my code:

typedef struct {
    int x;
    int y;
    char style;
} Pixel;

Pixel *pixels = (Pixel *)malloc(9*128);
emd22
  • 1
  • 1

2 Answers2

2

The problem is that you are calling malloc outside function.

This will solve your problem:

typedef struct {
    int x;
    int y;
    char style;
} Pixel;

int main(void) {
    Pixel *pixels = malloc(9 * 128);
}

In C you cannot call function on variable init, if variable is not inside any function.

int a = 5; //OK
int b = myfunc(); //ERROR, this was your case
int main() {
    int c = 5; //OK
    int d = myfunc(); //OK
}

As from code inspect, I assume you think that your sizeof(Pixel)is 9 bytes but this may not be the case. When you call your malloc, use this code:

Pixel *pixels = malloc(sizeof(Pixel) * 128);

This code will allocate memory for 128 Pixel structures in a single row on any platform.


Further reading:

Structure padding and packing

Do I cast the result of malloc?

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
1

This code aparently is not in any function. Then the expression following = can only be an initializer, and an initializer must be static (i.e. can be calculated at compile time) However, a call (to malloc in this case) can only be in a function. So the compiler complains.

The following would be correct:

typedef struct {
    int x;
    int y;
    char style;
} Pixel;

int main(void)
{
    Pixel *pixels = (Pixel *)malloc(sizeof(Pixel)*128);
    //...
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41