From: cplusplusquestion on
There is an array:
int a[MAX];

and the function will return a[MAX] value:

int* return_a_value(){
return a;
}

Is this code correct?
From: Richard Heathfield on
cplusplusquestion(a)gmail.com said:

> There is an array:
> int a[MAX];
>
> and the function will return a[MAX] value:
>
> int* return_a_value(){
> return a;
> }
>
> Is this code correct?

It isn't clear what you mean by "will return a[MAX] value" but, since there
is no value available at array element a[MAX], it seems you may want to
return the entire array. The above code will not achieve this. Instead, it
will return &a[0]. That is probably adequate for your needs, however.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
From: cplusplusquestion on

> It isn't clear what you mean by "will return a[MAX] value" but, since there
> is no value available at array element a[MAX], it seems you may want to
> return the entire array. The above code will not achieve this. Instead, it
> will return &a[0]. That is probably adequate for your needs, however.
>

for example:

const int MAX=20;
int a[MAX];

int* return_a_value(){
return a;
}

int main(){
for(int i=0; i<MAX; i++)
a[i] = 2;
int* b = return_a_value();
/******
access b's value
*****/



}

From: Richard Heathfield on
cplusplusquestion(a)gmail.com said:

>
>> It isn't clear what you mean by "will return a[MAX] value" but, since
>> there is no value available at array element a[MAX], it seems you may
>> want to return the entire array. The above code will not achieve this.
>> Instead, it will return &a[0]. That is probably adequate for your needs,
>> however.
>>
>
> for example:
>
> const int MAX=20;
> int a[MAX];
>
> int* return_a_value(){
> return a;
> }
>
> int main(){
> for(int i=0; i<MAX; i++)
> a[i] = 2;
> int* b = return_a_value();

b now points to a[0]. Obviously *b will be 2, which doesn't help us much.
But if we change the code to this:

for(int i=0; i<MAX; i++)
a[i] = i;
int* b = return_a_value();

we can now say that *b will be 0.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
From: cplusplusquestion on

>
> for(int i=0; i<MAX; i++)
> a[i] = i;
> int* b = return_a_value();
>
> we can now say that *b will be 0.

const int MAX=20;
int a[MAX];

int* return_a_value(){
return a;

}

int main(){
for(int i=0; i<MAX; i++)
a[i] = 2;
int* b = return_a_value();

for(int i=0; i<MAX; i++)
cout << b[i] << " "; // DOES this right?

return 0;
}