Sign in to follow this  
onehundred

Passing arrays of pointers...

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
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[i] = (int *) malloc(sizeof(int));
}

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

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this