today I encountered a problem with the dynamic creation of char arrays.
The following code is an example which causes the issues:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void){
char** top = NULL;
top = malloc(30*sizeof(char));
printf("sizeof top:%d\n",sizeof(top));
for(int i = 0; i < sizeof(top); i++){
top[i] = malloc(12*sizeof(char));
strcpy(top[i],"Lorem Ipsum");
}
for(int i = 0; i < sizeof(top); i++){
printf("%d: %s\tsize: %d\n",i,top[i],strlen(top[i]));
}
}
The expected output would look like this:
sizeof top:30
0: Lorem Ipsum size: 11
1: Lorem Ipsum size: 11
2: Lorem Ipsum size: 11
3: Lorem Ipsum size: 11
4: Lorem Ipsum size: 11
5: Lorem Ipsum size: 11
6: Lorem Ipsum size: 11
7: Lorem Ipsum size: 11
but instead I get this output:
sizeof top:8
0: size: 0
1: Lorem Ipsum size: 11
2: Lorem Ipsum size: 11
3: Lorem Ipsum size: 11
4: Lorem Ipsum size: 11
5: Lorem Ipsum size: 11
6: Lorem Ipsum size: 11
7: Lorem Ipsum size: 11
I already tried to change the size of all arrays but it keeps unchanged. I really don't understand why the size of top stays at 8 even i try to allocate more memory and why the first string stored to the arrays won't be shown correctly while the others do. After some research i couldn't find any information about similar problems. Someone could please explain this situation to me or recommend a reliable source?
Thanks in advance!
EDIT: I thought the issue had to do with the usage of the char** array (which it kind of did). I was unaware that the real issue was the value returned by sizeof. Thanks a lot for your kind answers and the quick aid.