-
printf of struct member
Hi
This is probably a common mistake but I still don't understand why I get an error.
I have an .h file where I declare a struct (and functions):
Code:
struct _HNum;
typedef struct _HNum HNum;
In a .c file I define the struct as following and lets say allocate some memory to it:
Code:
struct _HNum {
int sign; // 0 is + , 1 is -
int noofdigits; // no of elements in digits
int nofndigits; // no of nonzero elements in digits
char *digits;
};
HNum *HNum_alloc() {
HNum *H = (HNum*)malloc(sizeof(HNum));
//if( H != NULL )
//{
H->sign=0;
H->noofdigits=0;
H->nofndigits=0;
H->digits = (char*)calloc(10,sizeof(char));
//}
return H;
}
In my main file I then want to check if it works and did:
Code:
HNum *n1 = HNum_alloc();
printf("%i",n1->sign);
HNum_free(n1);
When I compile I get the error:
error: dereferencing pointer to incomplete type
at the printf line.
I don't understand why n1->sign does not access the right thing.
Thanks for any tips!
-
You don't have a structure prototype that your main file can see. You should move the
to the header file so that all the files can understand what is inside of it.
You have told main it's a data type but that's all that it knows
-
Thanks for you reply.
So if I understood well then I cannot access from main the members of the structure. If I DON'T want to include the statement you proposed into main I can still write a function in my .c and .h file which prints those members and call it from main. This should work, correct?
Thanks.
-
I believe you understand correctly. Your proposition will work: see the accessor suggestion below for it will be more versatile.
The way you have your code, main will not be able to see the struct member.
Since it is a pointer and you know what is inside of the struct, the 'int sign' is first, you could cast the pointer to an int*. This would only work if the int was at the beginning, by providing the struct {foo;}; c automatically knows the offset of each different member in a struct.
Code:
HNum *n1 = HNum_alloc();
printf("%i",(int*)n1);
HNum_free(n1);
In order to access a subsidiary of a struct you must have the structure definition somewhere in that file. By putting it in the header file the c preprocessor will add that to your main c file. If you don't want to put the struct definition in the header you can also just write the struct definition again in the main file (it doesn't have to be the same inside either). If you flat out don't want to let main know what's inside of the struct you will have to provide what in OO would be called an accessor function to get the value of that struct member.
such as:
Code:
(In the file where you have the HNum_alloc())
int getsign (struct *_HNum)
{
return _HNum->sign;
}
In c however, you would usually just allow everyone to see the struct definition.