简体   繁体   中英

C dynamic allocation malloc struc

I'm going through the practicals for my operating systems course and I can't get my head around this example. I've run the program and it does not work.

#include <stdio.h>

typedef struct {
int age;
float height;}Person;

void init(Person *);
int main() {

Person *Callum;
Callum = malloc(sizeof(*Callum));
init(Callum);
printf("Age: %d, height: %f\n", Callum.age, Callum.height);}

void init(Person * individual)
printf("Age: "); scanf("%d", &(individual->age));
printf("Height: "); scanf("%f", &(individual->height));}

I'm going to try to explain what I think is happening and if you could correct my logic I would be very grateful:

  • We have a pointer called Callum of type Person.
  • 'Callum = malloc(sizeof(*Callum));' => Does this mean our variable callum has been allocated the memory size of our struct on the heap?
  • Person points to our variable Callum. Edit: Sorry I got confused typing it out, I meant individual is pointing to our struc Person.
  • The program reads in an input and assigns it to the address of individual, which is the location of our variable Callum. We then print the values of Callum.

Sorry, this is rattling my brain. I know the basic mechanics of a struc and a pointer but I just can't visualize what is happening. Any help would be appreciated. Thank you.

In your code,

  void init(Callum * individual)

is wrong. You need to write

  void init(Person * individual)

as Person is the data type. Also, the function should be enclosed in braces, same as main() .

Also, in your main() , as the Callum is pointer type, you should use the pointer member dereference operator ->

 printf("Age: %d, height: %f\n", Callum->age, Callum->height);

That said, regarding the questions

  • Callum = malloc(sizeof(*Callum)); => Does this mean our variable callum has been allocated the memory size of our struct on our heap?
  • Yes, as long as malloc() is success.
  • Person points to our variable Callum
  • Not really. The correct way to express is Callum is a variable of type pointer to Person .

你需要做:

printf("Age: %d, height: %f\n", Callum->age, Callum->height);}

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