apple
apple

Reputation: 63

How to manage passing a pointer to an array to a function

I have a buffer of points that I want to send off to be processed by a function. It is an array of unsigned shorts. Currently I'm trying the following:

void ftn(unsigned short **buffer, int size)
{
    for (int i = 0; i < size; i++)
    {
        *(buffer[i]) = 0; //test
    }
}

Outside of the function, it's defined as unsigned short buffer[size]; Does this not make sense? Where am I going wrong? Thanks

Upvotes: 1

Views: 185

Answers (3)

When you pass an array to a function, you don't actually pass the array by value. Rather, you actually pass a reference to the original array.

Therefore, you simply need to do:

void ftn(unsigned short buffer[], int size)
{
    for (int i = 0; i < size; i++)
    {
        buffer[i] = 0; //test
    }
}

Note that if you change the actual value of buffer, you don't actually change the original array. An example of this could be:

void ftn(unsigned short buffer[], int size)
{
    buffer = new unsigned short[20];
}

If you wish to change the original array, your construct will work, but with a little modification:

void ftn(unsigned short **buffer, int size)
{
    for (int i = 0; i < size; i++)
    {
        (*buffer)[i] = 0; //test
    }
}

This is very C-like, mind you, and less C++-like.

buffer is a pointer to a pointer to an unsigned short. (That is, a pointer to the variable you use to refer to the array.)

If you dereference buffer, you get a pointer to an unsigned short, which can be treated as an array of unsigned shorts.

With this you also have the ability to reassign the value of the original variable, for instance like this:

void ftn(unsigned short **buffer, int size)
{
    *buffer = new unsigned short[20];
}

See also:

Upvotes: 3

Poni
Poni

Reputation: 11317

The answer is very quick, I don't know why people wrote so much:

#define SIZE_ARRAY 10

void ftn(unsigned short * buffer, int size)
{
    for (int i = 0; i < size; i++)
    {
        buffer[i] = 0; // test
    }
}

void main()
{
    unsigned short buffer[SIZE_ARRAY];
    ftn(&buffer[0], SIZE_ARRAY);
}

I wouldn't take Sebastian's answer he still uses unsigned short **buffer which is just too complication.

Upvotes: 0

Dhaivat Pandya
Dhaivat Pandya

Reputation: 6536

No that doesn't make sense, because buffer[i] "returns" an array of shorts, and the *(buffer[i]) tries to dereference that array of shorts, and then, you try to set a memory address for that (i.e. NULL or 0), and that results in a seg fault.

Upvotes: 0

Related Questions