How to define a pointer to a structure

I know this is a very simple problem, but I cannot move forward without it, and it is unclearly explained elsewhere.

Why does this programming give me so many undeclared identifier errors? However, I stated this.

This is the error I am getting.

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

and much more...

#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);

}
+5
source share
6 answers
typedef struct contactInfo
{
    int number;
    char id;
}ContactInfo;

This code defines 2 things:

  • type named ContactInfo
  • a structwith the nameContactInfo

Pay attention to the difference in cand c!

In your code, you are using a mixed combination of both, which is allowed (although confusing IMHO).

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));    
}

( / )

+4

:

ptr=(contactInfo*)malloc(2*sizeof(contactInfo));

, contactInfo.

a struct contactInfo, typedef: d contactInfo. C ( struct , ++).

, :

ptr = malloc(2 * sizeof *ptr);

malloc() C, . , , , .

, sizeof *ptr " , ptr ", .

+3

ptr=(contactInfo*)malloc(2*sizeof(contactInfo));

ptr=malloc(2*sizeof(struct contactInfo));
0

C - .

ptr=(contactInfo)malloc(2*sizeof(contactInfo));

:

ptr=malloc(2*sizeof(ContactInfo));

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

typedef, , , , , , typedef, .

  ContactInfo nom,*ptr;

, C , , typedef. C contactinfo

typecastingthat you do should not be done and be considered bad practice. Because it void *automatically and safely advances to any other type of pointer in this case malloc.

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

here you use contactInfo for typcast where struct contactInfo should be. and since you entered it in ContactInfo, you can also use this.

    struct contactInfo nom,*ptr;
    ptr=(ContactInfo*)malloc(2*sizeof(ContactInfo));
-1
source

All Articles