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

Recommended Answers

All 5 Replies

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.

haha yes, but I meant c++ style vs c-style.

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.)

How about

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

>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 ;)...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.