1

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

2
  • 2
    dim->height, dim->width and dim->name -- dim is a pointer so you use the -> operator to reference members. If dim were NOT a pointer, but a declaration of type struct Dimension itself, then you would use the . operator to access the members. Commented Aug 26, 2020 at 1:34
  • 1
    Assuming that char name would contain more than one character, you better change its definition to char *name (a pointer, pointing to a collection of characters, sized dynamically) or char name[20] (an array of characters of fixed size). Commented Aug 26, 2020 at 1:44

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.