Passing array of structures by pointer

This is a discussion on Passing array of structures by pointer within the C Programming forums, part of the General Programming Boards category; Hi there, I have been trying to write a simple program to pass an array of structures via pointer. I'm ...

Passing array of structures by pointer

Hi there, I have been trying to write a simple program to pass an array of structures via pointer. I'm sorry if this is a trivial question, and I'm sure it has been asked many times before. I have looked on google, however haven't managed to find exactly what may be wrong with my code. Any help would be much appreciated, thanks, Ed

p.s. I have tried allocating memory using malloc but got even more compile errors..

Next, understand that you're just declaring a pointer. This does not automagically create something for it to point to -- you have to do that yourself. Therefore you would need to do something like this:

Code:

card_t table[20]; // declare an array of 20 card_t's
card_t (*card_table)[20] = &table; // declare and define pointer-to-array of 20 card_t's
/* use it */
void assign()
{
int w=3;
(*card_table)[0].w = w; // dereference card_table to get to table, [0] to access the 1st structure and .w to get the w member of it
}

Notice the rather complex syntax for accessing members of a structure in the array. It would be much easier to go with the malloc approaches suggested above.

If you are going the malloc route you don't need to dereference as show in my example. Instead, the following should work for accessing structure members. This is because now there is one less level of indirection.

Code:

card_table[0].w = w; // likewise elsewhere

You should also check that malloc was able to allocate the requested memory. Check out the documentation for malloc function for hints on how to do that.