Jump to content
  • Advertisement
Sign in to follow this  
onehundred

Passing arrays of pointers...

This topic is 5049 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey guys, just been reading up on passing arrays of pointers as arguements and was shown this funtion
void display_array(int *q[])
{
      int t;
      
      for(t=0;t<10;t++)
       printf(" %d",*q[t]);
}
ok so far, but i've just been wondering how the mechanics of it works. Like would I make an array of pointers previously and assign memory addresses then pass the first element? I'm just a bit unsure what the options are. Regards OH

Share this post


Link to post
Share on other sites
Advertisement
int *data[5];

int v1 = 5, v2 = 4, v3 = 3, v4 = 2, v5 = 1;

data[0] = &v1;
data[1] = &v2;
data[2] = &v3;
data[3] = &v4;
data[4] = &v5;

display_array(&data[0]);

display_array(data);

If for example your array had 5 elements (cant be bothered typing 10) you could use the function these two ways.

Just like any array, "data" is simply a pointer to the first element in the array. This can lead to many problems as C does not check to see if the element you are indexing actually belongs to that array.

Check it out, only define the array with 5 elements, your function will still display 10 values, if none of the memory is protected.

Share this post


Link to post
Share on other sites
What davidx9 said is correct so I won't bother repeating. However you might also want to know that assigning data in his example is not always what you will want to do in more complex programs so you will need to read up on functions like malloc and free. i.e

int *data[5];

The code below will assign memory for your pointers to point to.

for(i = 0; i < 5; i++)
{
data = (int *) malloc(sizeof(int));
}

and then this code frees the memory once you are done.

for(i = 0; i < 5; i++)
{
free(data);
}

Share this post


Link to post
Share on other sites
ahhh yes, i know those functions - > creating a pointer to memory locations on the free store and then freeing it.

Cheers for the help guys

OH

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!