double pointers

hi!
I am trying to understand pointers, so I want to convert a char str[100][100] to char **p

I tried something like this:
char *p2;
p2 = &str;
p = &p2;

but didn't work.

Any ideeas? Thx
try p = str
N-Dimensional arrays are like N-Dimensional pointers to the first element
no, same error: cannot convert from 'char [100][100]' to 'char **'
what is your compiler?
There is only one direct/ implicit (does not need a cast) pointer assignment for that array:
1
2
char str[100][100];
char (*pCharArray)[100] =  str;


Now you have a pointer to char[100] - which can be safely treated as a char* - if you take the adress of this pointer then you will have a char** - but you will need a cast of one sort or the other.
1
2
3
4
char str[100][100];
char (*pCharArray)[100] =  str;
char **ppChar1 =  (char**)& pCharArray; //C-style cast
char **ppChar2 = reinterpret_cast<char**>(&pCharArray); //C++ stylee 


The question of course why you need to do something like this???
Last edited on
Thanks, the last post really helped me!
hello adrian89,

cannot convert from 'char [100][100]' to 'char **'
Like it says: Don't do it because they're different types.

they might look alike but are handled completely different internally.
+1 to coder777

if you have str[100][100] you cannot convert it to a char** (at least not in the way you're looking for). It simply is not possible. Any kind of forcible cast will fail horribly.


Here is some further reading: http://cplusplus.com/forum/articles/17108/


Of course, you probably shouldn't be using char arrays anyway. If you have an array of strings instead of an array of char arrays, this is a nonissue.
my cast is perfectly legal
guestgulkan wrote:
my cast is perfectly legal

well then
1
2
3
4
5
6
7
8
void main()
{
  char str[100][100];
  char (*pCharArray)[100] =  str;
  char **ppChar1 =  (char**)& pCharArray; //C-style cast

  ppChar1[1][1] = '1';
}
try this and see what happens it will crash
Last edited on
ppChar1[1][1] = '1';
of course it will crash.

ppChar1[x][1] where x is greater than 0 is an array out of bounds access;

You need to review your arrays and pointer stuff.



(p.s I'm not trying to have a go at you in any way)
Disch wrote:
if you have str[100][100] you cannot convert it to a char** (at least not in the way you're looking for)


Of course you can find a way to cast it to char**, but it will be useless. He's looking to have a char** that he can treat as a 2D array which, in this case, is impossible to do with casting alone.


EDIT:

Also your cast is more complicated and funky than the below, which is exactly the same but requires no casting:

1
2
3
char str[100][100];
char* badidea = &str[0][0];
char** ptr = &badidea;
Last edited on
Topic archived. No new replies allowed.