How to convert char[][] to char** ?
Sep 10, 2012 at 5:15am UTC
I have a char 2d array :
char s[5][5];
//s[0][0] = ... s[0][1] =....
printf("%s",s[0]); //it's ok
char **foo;
*foo = &s[0][0];
printf("%s",foo[0]);
it cause segmentation fault !
Sep 10, 2012 at 5:37am UTC
1 2
char **foo;
*foo = &s[0][0]; // <- this is wrong. This is where you're segfaulting
foo is a pointer (a pointer to a char*).
on the 2nd line here you are dereferencing it... but it doesn't point to anything. So you are assigning &s[0][0] to random memory. That's why you segfault.
You probably want this:
1 2 3
char * foo = &s[0][0]; // or just: char* foo = s[0];
printf("%s" ,foo);
-------------
or....
If you want foo to point to s... like...
char ** foo = s;
, that is not possible because s is not an array of pointers, it's an array of arrays.
You'd have to change foo to be a pointer to an array in that case:
1 2 3
char (*foo)[5] = &s;
printf("%s" ,foo[0]);
--------------
but of course if you can use C++ you don't have to muck around with this crap and you can just use strings. Much simpler and safer.
Last edited on Sep 10, 2012 at 5:38am UTC
Topic archived. No new replies allowed.