int*和Type*之间有区别吗?

Ail*_*lyn 3 c pointers

我在C中实现一个队列.我有一个像这样的结构:

struct Node {
    Node* next;
    Node* previous;
    // data
}
Run Code Online (Sandbox Code Playgroud)

因为next并且previous只是指针,如果我使用Node*或者它会有所作为int*吗?例如:

struct Node {
    int* next;
    int* previous;
    // data
}
Run Code Online (Sandbox Code Playgroud)

San*_*nto 8

它不仅为您的代码带来了清晰度(重要的是,您的项目越大),如果您正在对正确的类型进行数学运算,指针数学只能正常工作.在您的实例中,向Node*添加1将导致将sizeof(Node)添加到基指针,这几乎保证不会是== sizeof(int).

对于你给出的例子,它可能不重要(但你需要一个演员)..但是帮自己一个忙,并养成使用正确类型的好习惯.


R..*_*R.. 5

使用int *不正确并导致未定义的行为.你可以使用或者,Node *或者void *如果你使用除了之外的任何类型Node *,它将需要一个强制转换(或隐式转换,例如通过赋值)回到Node *你可以取消引用它之前.