如何定义指向结构的指针

SLe*_*ner 5 c pointers structure

我知道这是一个非常基本的问题,但如果没有它我就无法前进,而且其他地方也没有明确解释.

为什么这个编程给了我很多未声明的标识符错误?不过我已经宣布了.

这些是我得到的错误.

Error   2   error C2143: syntax error : missing ';' before 'type'
Error   3   error C2065: 'ptr' : undeclared identifier
Error   4   error C2065: 'contactInfo' : undeclared identifier
Error   5   error C2059: syntax error : ')'
Error   15  error C2223: left of '->number' must point to struct/union
Run Code Online (Sandbox Code Playgroud)

和更多...

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

typedef struct contactInfo
{
    int number;
    char id;
}ContactInfo;


void main()
{

    char ch;
    printf("Do you want to dynamically etc");
    scanf("%c",&ch);
    fflush(stdin);


        struct contactInfo nom,*ptr;
        ptr=(contactInfo*)malloc(2*sizeof(contactInfo));

    nom.id='c';
    nom.number=12;
    ptr->id=nom.id;
    ptr->number=nom.number;
    printf("Number -> %d\n ID -> %c\n",ptr->number,ptr->id);

}
Run Code Online (Sandbox Code Playgroud)

Veg*_*ger 5

typedef struct contactInfo
{
    int number;
    char id;
}ContactInfo;
Run Code Online (Sandbox Code Playgroud)

这段代码定义了两件事:

  1. 命名ContactInfo
  2. 一个struct有名的contactInfo

注意的区别cC

在您的代码中,您使用的是两者的混合组合,这是允许的(尽管恕我直言令人困惑)。

如果您使用struct变体,则需要明确使用struct contactInfo. 对于另一个变体 ( ContactInfo),您必须省略该struct部分,因为它一直是类型定义的一部分。

所以要小心你的结构的两种不同定义。最好是只使用其中一种变体。


我手头没有 Visual Studio,但以下(更正的)代码使用 gcc 正确编译,没有任何警告:

#include<stdlib.h>

typedef struct contactInfo
{
    int number;
    char id;
}ContactInfo;


void main()
{
    ContactInfo nom,*ptr;
    ptr=malloc(2*sizeof(ContactInfo));    
}
Run Code Online (Sandbox Code Playgroud)

(我省略了代码中不太有趣/未修改的部分)