Mgert33
Mgert33

Reputation: 101

malloc with structs and how to access memory of malloc of struct

if i have a simple struct such as How would i got about dynamically allocating memory for this struct using malloc?

struct Dimensions{
int height, width;
char name;
};

I um unsure on how to go about this, I have tried

struct Dimension* dim = malloc(sizeof(struct Dimensions));

Also I would like then access the height and width variable in a loop later on in my code. My first thought would be to use a pointer but im unsure on what this would exactly be.

Would it be something like

int h = *width

I'm very new to C. Thanks

Upvotes: 1

Views: 1185

Answers (1)

tdao
tdao

Reputation: 17668

The way you dynamically allocated that struct is correct:

struct Dimension* dim = malloc(sizeof(struct Dimensions));

Also I would like then access the height and width variable in a loop later on in my code.

You should first assign some value to that dim first, something like:

dim->high = 1;
dim->width = 2;

The name member you just used a char which might not be what you need. Usually it's a string: char name[100];. You can't use assignment for that string though, so use strcpy.

Then you can access that later:

int h = dim->high;

Remember once you're done with the dynamically allocated memory, you should free it:

free(dim);
return 0;

Upvotes: 2

Related Questions