For example I have a struct
struct s{
char c;
int x;
};
And I use calloc() to allocate memory.
s *sp = (s*) calloc(1, sizeof(s));
Now, what will be the values of sp->c and sp->x?
For example I have a struct
struct s{
char c;
int x;
};
And I use calloc() to allocate memory.
s *sp = (s*) calloc(1, sizeof(s));
Now, what will be the values of sp->c and sp->x?
"What will be the values of
sp->candsp->x?"
Since calloc() sets all bits of the allocated memory to 0, c and x will have the value of 0 if the 0 value representation of int and char is of all bits to 0 (which is common).
Note that in the case of pointers, the pointer might not be standard-compliant NULL pointer when just setting all bits to 0 as the C standard does not require the representation of NULL pointers to be all-zero-bits.
Side notes:
1.
struct s{
char c;
int x;
};
s *sp = (s*) calloc(1, sizeof(s));
can´t work as s isn´t a typedefd type; it is a structure tag. Therefore, You need to precede s by the struct keyword:
struct s *sp = (struct s*) calloc(1, sizeof(struct s));
2.
You do not need to cast the returned pointer from calloc() and other memory management functions and rather avoid it since it can add clutter to your code. -> Do I cast the result of malloc
So, just do:
struct s *sp = calloc(1, sizeof(struct s));