I have a buffer of points that I want to send off to be processed by a function. It is an ar开发者_开发知识库ray 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
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 short
s.
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:
- Arrays as parameters
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.
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.
精彩评论