Originally Posted by
skyr6546
I wrote code like this
Code:
#include<stdio.h>#include<stdlib.h>
struct Name{
char n;
char m;
struct Name *N;
};
void main (){
struct Name *H = (struct Name*)malloc(sizeof (struct Name));
H->n;
H->m;
H->N;
printf("%d \n", sizeof (H->n));
printf("%d \n", sizeof (H->m));
printf("%d \n", sizeof (H->N));
printf("%d \n", sizeof (struct Name));
}
When I ran code
It gives below output
1
1
4
8
so I understand
H->n; take one byte
H->m; take one byte
result say H->N; 4 bytes
I do not understand why does it take 4 bytes ?
The actual values you get will be system dependent. I cleaned you code up to get rid of the basic warnings it generates add ran it on my system.
Code:
#include<stdio.h>
#include<stdlib.h>
struct Name{
char n;
char m;
struct Name *N;
};
int main (){
struct Name *H = malloc(sizeof (struct Name));
if (H == NULL) {
fprintf (stderr, "Malloc failed\n");
exit(EXIT_FAILURE);
}
printf("%ld \n", sizeof (H->n));
printf("%ld \n", sizeof (H->m));
printf("%ld \n", sizeof (H->N));
printf("%ld \n", sizeof H);
printf("%ld \n", sizeof *H);
printf("%ld \n", sizeof (struct Name));
free (H);
return 0;
}
On the system I'm using compiled with:
gcc -std=c11 -Wall size_struct.c -o size_struct
I get:
1
1
8
8
16
16
I'm using a 64 bit system so pointers are 8 bytes in size (8*8=64). My compiler has added padding to the struct to aid alignment. I used the specifier %ld because the return value of sizeof is a long int.
For every malloc in your program you should call free - an you should get in the habit of checking the return value. It may seem like a lot of extra typing for an example but it's a habit worth cultivating.
Worth noting is that the pointer N is never initialized so will not be valid and shouldn't be de-referenced until it is initialized.
sizeof is actually an operator and when referring to an actual object you can call it without brackets.
There may be things your compiler can tell you to help you learn C. Learning to turn the warnings up and then trying to understand them so you can clean up your code (that would be compiler dependent of course) can be very valuable.
-Greg.