Click to See Complete Forum and Search --> : C++ question
Paolo Giustinoni
January 7th, 2002, 08:51 AM
I have one question... I have to pass as argument an array of string to a function that has an array of pointer to void as argument, but my code, that's like this:
//
void f(void *ptr[])
{}
//
int main()
{
//
string str[2] = {"hello", "world"};
f(....);
//
}
doesn't work.
Can somebody help me?
Andreas Masur
January 7th, 2002, 10:02 AM
Take a look at the following sample...
void Function(void *ptr[])
{
cout << *(reinterpret_cast<string *>(ptr[1]));
}
int main()
{
string **ppStrings = new string *[2];
ppStrings[0] = new string("hello");
ppStrings[1] = new string("world");
Function(reinterpret_cast<void **>(ppStrings));
for(int iCnt = 0; iCnt < 2; ++iCnt)
delete ppStrings[iCnt];
delete ppStrings;
return 0;
}
Ciao, Andreas
"Software is like sex, it's better when it's free." - Linus Torvalds
prufus
January 7th, 2002, 10:04 AM
A string is a class so you're declaring an array of class OBJECTS not an array of pointers which you need. To use the following function:
void f(void * ptr[]);
you need to do something like this:
//declare an array of pointers to string
string * string_ptr_array[2];
string_ptr_array[0] = new string("hello");
string_ptr_array[1] = new string("world");
f(reinterpret_cast<void **>(string_ptr_array));
delete string_ptr_array[0];
delete string_ptr_array[1];
within the actual function you might do something like this:
void f(void * ptr[])
{
string ** str_ptr = reinterpret_cast<string**>(ptr);
cout << *(str_ptr[0]) << "\n";
cout << *(str_ptr[1]) << "\n";
}
To use your original declaration:
string str[2] = {"hello", "world"};
f( (void*)str );
Your function had to have been declared like the following:
void f( void * ptr)
{
string * str_ptr = reinterpret_cast<string*>(ptr);
cout << str_ptr[0] << "\n";
cout << str_ptr[1] << "\n";
}
Hope this helps.
Paolo Giustinoni
January 7th, 2002, 12:08 PM
Thanks a lot. Very helpful.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.