Trying to allocate a char array of N elements.
#include <stdio.h>
#include <malloc.h>
int main()
{
int N = 2;
char *array = malloc(N * sizeof(char));
array[0] = 'a';
array[1] = 'b';
array[2] = 'c'; // why can i do that??
printf("%c", array[0]);
printf("%c", array[1]);
printf("%c", array[2]); //shouldn't I get a seg fault here??
return 0;
}
The question is:
Since I am allocating 2 * 1 = 2 bytes of memory that means i can have 2 chars in my array. How is it possible that I have more?? I also printed sizeof(*array) and it prints 8 bytes. What am I missing here?
sizeof(*array)should be 1, not 8. Maybe you printedsizeof(array), which gives the size of a pointer.arrayis actually a pointer, not an array.