I am confused as to what the sizeof
function returns.
Suppose I enter the following into a program for sizeof
, and this is what is returned:
sizeof(char) == 1
sizeof(int) == 4
sizeof(float) == 4
sizeof(long) == 8
sizeof(double) == 8
sizeof(void *) == 8
sizeof Pointer
is 8.
So if I malloc
a long array:
long *array = (long *)malloc(64)
Would this sizeof()
inserted into the malloc
of my long array be equivalent?
long *array = (long *)malloc(8*sizeof(long))
Now if I have a struct:
typedef struct treenode {
struct treenode *left;
struct treenode *right;
void *content;
} Treenode;
And I run sizeof(Treenode)
, do I add all the elements of the struct together?
Pointer + Pointer + void * = 8 + 8 + 8 = 24
I tried running this in a program, however I get sizeof(Treenode)
to return 12.
I am also wondering why when I create a new struct like this:
typedef struct country {
char city[40];
int population;
int rank;
}
and try to malloc(sizeof(country *))
only 8 bytes are allocated instead of the bytes of the struct.
Finally when I do sizeof("Korea")
, why is my return value 6 and not 5? Should it not be 5 because there are only 5 chars in the string?