0

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?

Seraphine
  • 29
  • 2
  • More or less unrelated, but (0) you don't call variables and (1) it makes the code clearer if you use different type names. I'd typedef that as person and *pPerson - the point being to add a 'p' to pointer types. In a recent project, I've got `typedef struct{float x,y,z} vec3, *pVec3;` – enhzflep Aug 23 '22 at 00:01
  • 4
    I wouldn't `typedef` the pointer at all - hiding a variable's type does not help, especially when you can't tell what's going on. – Andrew Henle Aug 23 '22 at 00:09
  • I may not express my meaning clearly, what I mean is that I think the `typedef struct Per *Person` I use, where `Person` itself is already a pointer type, it should not be equivalent to `*Per` in theory, that is, `*Per` = `Person`, That is to say, the function `void InitPerson(Person p)` should be equivalent to `void InitPerson(Per* p)`, right? – Seraphine Aug 23 '22 at 00:09
  • 5
    If you really want to make your code crystal clear, [don't hide pointer types behind typedef aliases **at all**](https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers). There are very, *very* few instances where it make sense to do so, and *none* of them are present in the posted code. C engineers want to "see the splats". They're the calling card of a pointer variable and are instantly known at definition location. Hiding them makes it harder, not easier, to manage the code. Just... don't. – WhozCraig Aug 23 '22 at 00:10
  • yes ```Person p``` is equivalent to ```Per* p``` – programme3219873 Aug 23 '22 at 00:14
  • Sorry, the above is wrong, I mean Person is equivalent to Per* – Seraphine Aug 23 '22 at 00:16
  • 1
    This looks like a bad habit picked up from CS50's `string s` instead of `char *s`... Lovely... – Fe2O3 Aug 23 '22 at 00:16

0 Answers0