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);
}
typedef struct contactInfo
{
int number;
char id;
}ContactInfo;
This code defines 2 things:
ContactInfo
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With