This gives seg fault. Why? Thanks.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { char buf[3][10]={"apple", "pineapple", "banana"}; char** ptr=(char**)buf; puts(*ptr); }
This gives seg fault. Why? Thanks.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { char buf[3][10]={"apple", "pineapple", "banana"}; char** ptr=(char**)buf; puts(*ptr); }
I can see you are casting buf in order to overcome compile errors, but that's just hiding the problem of your approach. You should appreciate that a multidimensional char array is NOT an array of pointers to strings. Try inserting the following and commenting out the puts().
In effect you create a pointer to pointer of chars 'ptr',Code:printf("buf = %p\nptr = %p\n*ptr = %p", buf, ptr, *ptr) ;
Assign the address of buf to ptr,
Dereference ptr in puts(), and puts takes the value stored at the address of buf and treats it as an address.
What is the value at the address at the start of buf ? (Hint: it's not an address)
Try the following,
Code:int main() { char buf[3][10]={"apple", "pineapple", "banana"}; char (*ptr)[10]; // = (char **)buf; ptr = buf ; puts(*ptr++); puts(*ptr++); }
Thanks tc. I've tried your code.
char (*ptr)[10] is different from char *ptr[10].Code:#include <stdio.h> #include <string.h> #include <ctype.h> int main() { char buf[3][10]={"pine", "apple"}; char (*ptr)[10]; ptr=buf; puts(*(ptr+1)); buf[0][0]='a'; puts(*ptr); ptr[0][0]='b'; puts(*ptr); // different from char (*ptr)[10] char *pointers[10]; char c='q'; pointers[0]=&c; putchar(*pointers[0]); // prints 'q' }
Indeed it is different.
char (*ptr)[10] specifies a single variable ptr that is a pointer to char arrays of 10 elements. I don't have to specify 10, I could just declare char (*ptr)[] and then it is a pointer to char arrays of any size, but then I can't use expression ptr++.
char *pointers[10] specifies an array named pointers that holds 10 pointers to char.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"