Search code examples
cmemorystructmemory-managementallocation

Dynamic Memory Allocation for Pointers inside Struct


A question with the same title has been asked before on Stack Overflow but it isn't the answer I am a looking for.

I am trying to create a pointer to a dynamically-allocated array containing the pixel data.

This is how I try doing it.

struct Image {
int width;
int height;
int* pixels = malloc((width * height) * sizeof(int));
};

Error Message

But I am getting an error expected a ';'

The same code outside the struct works fine.

Can someone please explain to me why this errror occurs.


Solution

  • The same code outside the struct works fine.

    Can someone please explain to me why this errror occurs.

    This is because a struct in C is something different than a struct C#:

    In C you cannot assign "default" values to struct members like this:

    struct myStruct {
        int a = 2;
        int b = 4;
    };
    

    You can only assign initial constant values to a variable that has a struct type:

    struct mystruct {
        int a;
        int b;
    };
    
    struct mystruct myvar = { 5, 6 }; /* myvar.a=5, myvar.b=6 */
    

    ... but because malloc() is a function call, the following line is also not possible in C:

    struct Image myVariable = { 10, 20, malloc(200) };
    

    You must initialize the field pixels "outside the struct".