when i run this i get segv on printf, what am i doing wrong?
int main() {
char **bla;
int size =10;
int i;
bla = calloc(size*size,sizeof(char *));
for(i=0;i<size;i++) {
*bla = calloc(10,sizeof(char));
strncpy(*bla,"aaaaa",size);
bla++;
}
printf("%s\n",bla[0]);
}
I know i could do this with
int main() {
char **bla;
int size =10;
int i;
bla = calloc(size*size,sizeof(char *));
for(i=0;i<size;i++) {
bla[i] = calloc(10,sizeof(char));
strncpy(bla[i],"aaaaa",size);
}
printf("%s\n",bla[0]);
}
but is there any way to do this with pointers?
By writing
bla++, you’re changingblato point to the next pointer.At the end,
bla[0](which is equivalent to*bla) has been incremented 10 times and will point the memory location immediately after the allocated block.You could fix this by writing
bla -= 10after the loop.However, the best way to fix it is to not increment
blaat all, and instead writeAlternatively, you could declare a second pointer (
char** currentBlah = blah) and increment it instead, then printblah[0], which will still point to the original memory location.