void* to char**

Hello, i'm having problems with static_cast. I'm trying to convert void* to char ** in this way:
1
2
3
4
5
6
7
DWORD WINAPI f(void *lp)
{
char **new_chars=static_cast<char**>(lp); // void * to char **

std::cout<<new_chars[0][0]; //seg. fault here!

}

what am i doing wrong?
You can't. You need reinterpret_cast.

You have a 'pointer to anything' and have decided to treat it as a 'pointer to a char*'. That is 'reinterpreting' the type of the memory without applying any conversions.
A 'fixed' code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
DWORD WINAPI f(void *lp)
{
char **new_chars=reinterpret_cast<char**>(&lp); // void * to char **

std::cout<<new_chars[0]; //everything is ok


std::cout<<new_chars[1]; //should display 'two' but program crashes here

}
int main()
{
char bda[2][20]={"one","two"}; 
f(bda);
getch();
}

so why cout <<new_chars[1]; crashes?
Yours shouldn't compile because f(bda) in main. It's crucial to decide what lp actually is, now that you've relieved the language from helping you. Is it the array or a pointer to the array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

void f(void* lp)
{
	char **new_chars=reinterpret_cast<char**>(lp);
	std::cout << new_chars[0];
	std::cout << new_chars[1];
}

int main()
{
	char* bda[2] = { "one", "two" };
	f(reinterpret_cast<void*>(bda));
}

Last edited on
Hmm... I think i have a bad habbit to mix pointers and arrays. By the way, f(bda) compiles.
Yes, you do. Why not just make the lp parameter a char[2][]?
I expect it's some kind of Windows callback where data often comes back in as void* or 32bit ints.
This thread = Reason #563 why multidimensional arrays suck.

Consider the following:
1
2
3
char foo[2][3];

void* bar = foo;


This compiles, but what exactly does 'bar' point to? You might get tricked into thinking that because you have char foo[2][3] that foo points to char**. However this is not true!

foo, when cast to a pointer, is not a double pointer (**), but is a pointer to an array:

1
2
3
4
5
6
7
8
9
10
char foo[2][3];

char (*bar)[3];  // a pointer to a char[3] array
bar = foo;

//---------------------
// or for a more readable way
typedef char char3[3];
char3* bar;
bar = foo;


This is what is happening with your void pointer.

But really -- the whole idea to use a void pointer here is a bad call. void pointers prevent the compiler from catching mistakes like this... so instead of compiler errors which are easy to find and fix, you're left with runtime errors that make your program explode.
Topic archived. No new replies allowed.