typedef with pointer in C [duplicate]

你说的曾经没有我的故事 提交于 2020-05-27 12:21:08

问题


I am beginner in C programming and I am studying on Linked Lists. I am trying to create a Linked List which is gonna display the letters in correct order. The program enables the user to insert a character in the list in alphabetical order or to delete a character from the list. So, I follow an example to a point but there is something that I cannot understand.

Here is the first part of the code:

#include <stdio.h>
#include <stdlib.h>

struct listNode {
    char data;
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

After that part, program starts with the function prototype. I know the usage of typedef in the second line from the bottom. But what I don't know is, the last line of the code which contains:

typedef ListNode *ListNodePtr;

What does that mean?


回答1:


Short version:

typedef ListNode *ListNodePtr;

defines ListeNodePtr as a pointer to ListNode.

You may wonder why the asterisk is "sticking" to ListNodePtr here. That's because in C declarations, being a pointer is considered a type modifier, so in a declaration, it's part of the declarator (the identifier of the variable or typedef'd type).(*) This is relevant as soon as you have multiple declarations in a single line, e.g. the following:

int *a, b;

would define a pointer to int a and a plain int b.

You could write it as

int* a, b;

but that would be very confusing, because b would still not be a pointer.

All that being said, I personally consider it bad style to typedef a pointer, because as a C programmer, you know the meaning of an asterisk. Hiding it behind a typedef (and as done here, replacing it by some non-standard suffix like "Ptr") just makes the code harder to read for others.

(*) added footnote here: the reasoning behind this design is that declarations should look the same as usage. *a dereferences a pointer, so *a should as well declare a pointer.




回答2:


typedef struct listNode ListNode;

The first line means ListNode will represent struct listNode.

typedef ListNode *ListNodePtr;

The second line means ListNodePtr will represent ListNode * which is a pointer to ListNode.




回答3:


A ListNodePtr holds a pointer to a ListNode. So if you unravel the typedefs, it's short for: struct listNode *.



来源:https://stackoverflow.com/questions/33188589/typedef-with-pointer-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!