I know that in C language, if you want to call the value of the source variable, you need to pass in the pointer of the source variable, but I don't understand why this code of mine goes wrong, although I know that the solution is to nest another layer of pointers, but I don't understand why is this wrong
#include <stdio.h>
#include <malloc.h>
typedef struct Per {
int index;
char name;
}Per,*Person;
void PrintPerName(Person p) {
printf("Per name:%c", p->name);
}
void InitPerson(Person p) {
p = malloc(sizeof(Per));
p->index = 0;
p->name = 'a';
}
//this is the “right” way
void InitPerson2(Person* p) {
*p = malloc(sizeof(Per));
(*p)->index = 0;
(*p)->name = 'a';
}
int main() {
Person p = NULL;
InitPerson(p);
PrintPerName(p);
return 0;
}
My problem is that I have used a typedef struct
to redefine the pointer of the Per
variable to the Person
type, so shouldn't the Person
variable itself be a pointer type? Should I pass and use the pointer's value if I pass a method the same way I pass a pointer?