1833016 Members
2161 Online
110048 Solutions
New Discussion

Pointer to arrays in g++

 
SOLVED
Go to solution
Alfonso_15
Advisor

Pointer to arrays in g++

Good Morning:
I have function returning a pointer to array (must be the first element in the array) like this:
...
#define VAR_SIZE1 256
unsigned int var1[VAR_SIZE];
unsigned int *get_address(){return (unsigned int *)var1;}
...
I need to customize a caller program:
...
unsigned int var2[VAR_SIZE];
var2 = get_address();

But the compiler outputs this error:
incompatible types in assignment of `unsigned int*' to `unsigned int[256]'

Guys: If I can not return arrays, how I can redefine my function get_address(), or how I must declare var2 in the caller program?
Thanks in advance for your help.
alfonsoarias
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Pointer to arrays in g++

You need to change:
unsigned int var2[VAR_SIZE];
to:
unsigned int *var2;

var2 = get_address();

but note that eventhough var2 is a pointer, you can still use it like an array so that
var2[12] = 609;
is perfectly valid.

Also there is no need to cast the rurn value of your function since an array without a subscript is a pointer.

unsigned int *get_address(void)
{
return(var1);
} /* get_address */

is perfectly legal.

If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Pointer to arrays in g++

I suppose that I should add that there is really no reason for your function since once you change
unsigned int var2[VAR_SIZE];
to
unsigned int *var2;

then this assignment is perfectly legal (and more readable).

var2 = var1;
var2[0] = 12;
If it ain't broke, I can fix that.
Alfonso_15
Advisor

Re: Pointer to arrays in g++

Perfect. Now my program is working. Thanks you soo much Clay.
alfonsoarias