CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: C++ question

  1. #1
    Join Date
    May 2001
    Location
    Italy
    Posts
    56

    C++ question

    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?


  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: C++ question

    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

  3. #3
    Join Date
    Jan 2002
    Location
    New York, NY, USA
    Posts
    4

    Re: C++ question

    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.


  4. #4
    Join Date
    May 2001
    Location
    Italy
    Posts
    56

    Re: C++ question

    Thanks a lot. Very helpful.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured