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:
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 variablecallum
has been allocated the memory size of ourstruct
on our heap?
malloc()
is success.
- Person points to our variable Callum
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.