3

I'm using Win32 API and the _beginthreadex call to run a thread the following way:

struct StructItem
{
   std::string title;
   int amount;
};

StructItem structItems[33];
unsigned int id;
HANDLE thread = (HANDLE)_beginthreadex(NULL, 0, my_thread, (void*)structItems, 0, &id);

And this is my thread:

unsigned int __stdcall my_thread(void *p)
{
    for (int i = 0; i < 20; i++)
    {           
        // todo: print struct.title
        Sleep(1000);
    }

    return 0;
}

As far as I understood the *p is a pointer to my list of structures, since I passed them to the 4th argument in the _beginthreadex call, but I can't understand how can I cast the *p so that I can access the array of structs from within the thread?

0x29a
  • 733
  • 1
  • 7
  • 23

2 Answers2

7

Since the array decays into a StructItem* (the location of the array's first element) when you pass it as an argument, cast it back to StructItem*.

unsigned int __stdcall my_thread(void *p)
{
    auto items = static_cast<StructItem*>(p);
    for (int i = 0; i < 20; i++)
    {           
        std::cout << items[i].title << '\n';
        Sleep(1000);
    }
    return 0;
}

Note that the cast to void* is entirely unnecessary.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
1

You could cast void pointer to the pointer type of your struct, and then dereferencing that pointer expression to get the element at a particular offset:

*((StructItem*) p); /* first element */
*((StructItem*) p+ 1); /* second element */

Its a c-style method. However I would rather prefer C++ style which is already answered.

Sumit Jha
  • 1,601
  • 11
  • 18