Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a pointer to a structure

I know this is a very basic problem, but I cannot move forward without it and its not clearly explained elsewhere.

Why is this programming giving me so many errors of undeclared identifier? I have declared it, though.

These are 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 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);

}
like image 616
SLearner Avatar asked Jan 23 '13 09:01

SLearner


2 Answers

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

This code defines 2 things:

  1. a type named ContactInfo
  2. a struct named contactInfo

Notice the difference of the c and C!

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

If you use the struct variant you need to explicitly use struct contactInfo. For the other variant (ContactInfo) you must to omit the struct part as it is part of the type definition alteady.

So be careful with both different definitions of your structure. Best would be to only use either one of the variants.


I do not have Visual Studio at hand, but the following (corrected) code compiles with gcc properly without any warnings:

#include<stdlib.h>

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


void main()
{
    ContactInfo nom,*ptr;
    ptr=malloc(2*sizeof(ContactInfo));    
}

(I left out the not so interesting/unmodified parts of the code)

like image 163
Veger Avatar answered Sep 20 '22 04:09

Veger


This:

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

is wrong, there's no type called contactInfo.

There's a struct contactInfo, which is typedef:d as ContactInfo. C is case-sensitive (and you must include the struct unlike how it works in C++).

Also note that the quoted line is better written as:

ptr = malloc(2 * sizeof *ptr);

Since casting the return value of malloc() is a bad idea in C, I removed the cast. Also, repeating the type is a bad idea since it makes the risk of introducing error greater, so I removed that as well.

Note that sizeof *ptr means "the size of the the type that ptr points at" and is a very handy thing.

like image 31
unwind Avatar answered Sep 18 '22 04:09

unwind