The output of the code has to be zero, but I am having an error, please guide. I can initialize the structure with its type variable but how can I do with the pointer to initialize the whole structure?
#include<stdio.h>
typedef struct student
{
int roll_id[10];
int name_id[10];
int postn;
} student;
int main()
{
student p; /// here i can do student p={ {0} };
student *pptr=&p;
pptr= { {0} }; /// but can i initialize in this way ?? //error: expected
expression before ‘{’ token
pptr->roll_id[9]=1;
printf (" %d\n", pptr->postn);
return 0;
}
4 Answers 4
As stated by chris on a comment, you are assigning "something not an integer" to a pointer. You should assign { {0} } instead to the content of that pointer (*pointer):
*pptr= { {0} }; //bad!
Anyway this is not the correct way to populate that structure and you should use:
*pptr= (student){ {0}, {0}, 0 };
as an example
edited to solve the error pointed by unwind
1 Comment
If all you want is a 0-initialized structure, you might as well do:
struct student *pptr = calloc(1, sizeof(struct student));
alternatively, following the code you posted:
struct student p;
struct student *pptr = &p;
memset(pptr, 0, sizeof(struct student));
of course, these approaches will only work if you want a 0-initialized struct. for anything more facy you'll have to write it out, or use some memcpy magic.
5 Comments
If you're using C99 or later, you can use compound literals. Otherwise you cannot, and must initialize each field separately.
With literals:
*pptr = (student) { 0, 0, 0 };
without:
pptr->roll_id[0] = 0;
pptr->name_id[0] = 0;
pptr->postn = 0;
UPDATE Edited, for some reason I thought that the roll_id and name_id fields were strings, but they're not.
It might be easier to just use memset() for this, to initialize all the values to zero:
memset(pptr, 0, sizeof *pptr);
Notice, as always, that this is a fantastic opportunity to use sizeof with the pointer, since reduces the typing and is easier to read and verify (for reasonable variable names such as we have here).
5 Comments
use as below
int main()
{
student p[] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
student *pptr = p;
pptr->roll_id[9] = 1;
printf (" %d\n", pptr->postn);
return 0;
}
if you want to initialize entire array that is a member of structure , you have to do as like above.
{ {0} }to a pointer.