If I do this, I get "warning: address of local variable returned".

unsigned char* CharArray(void) const
{
	unsigned char arr[3];
	arr[0] = R_;
	arr[1] = G_;
	arr[2] = B_;
	
	return arr;
	
}

So the reason for that is that the memory allocated for arr[] is only available within the scope of the function CharArray?

So instead do I do this:

unsigned char* CharArray(void) const
{
unsigned char* arr =  new unsigned char[3];
	arr[0] = R_;
	arr[1] = G_;
	arr[2] = B_;
	
	return arr;
	
}

Or I could pass a reference and fill it? How would I do that?

void CharArray(unsigned char* &arr)
{
	arr[0] = R_;
	arr[1] = G_;
	arr[2] = B_;
}

main()
{
unsigned char arr[3];
CharArray(arr);
}

Like is it a reference to a pointer? Or is it just

void CharArray(unsigned char &arr)

That seems like it is just a reference to a single unsigned char, not an array of them.

Which is the most modern (ie c++) way to do this?

Thanks!

Dave

You would just do this:

void CharArray(unsigned char* arr) {
...
}

int main() {
    unsigned char arr[3];
    CharArray(arr);
}

Which is the most modern (ie c++) way to do this?

C++ is over 20 years old.

In this situation you cannot use a reference. Think of a reference type as simply automating the address-taking and dereferencing. So this:

void x (char &a)
{
    a = 'x';
}

int main()
{
    char a;
    x (a);
}

Ultimately means this:

void x (char *a)
{
    *a = 'x';
}

int main()
{
    char a;
    x (&a);
}

If you study the above thoughtfully, you will see why there is no way to use references to do what you want. (Remember that a is "syntactic sugar" for *(a+i), so it involves pointer arithmetic and a manual dereference.)

>Which is the most modern (ie c++) way to do this?
To do - what?
What's a true problem? "Returning a pointer" is not a problem. All snippets in the original post describes different program cases.
It seems the right question only helps to correct this bla-bla-bla thread direction ;)...

This article has been dead for over six months. Start a new discussion instead.