简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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