?
Solved

explain in detail, please

Posted on 2003-03-26
10
Medium Priority
?
269 Views
Last Modified: 2010-08-05
include <iostream>
using namespace std;

int* foo(int* a)
{
     a = new int[10];
     for(int i = 0; i < 10; a[i] = i++);
     return a;
}
int main()
{
     int* a = 0;
     //works
        for(int i = 0; i < 10; i++) cout << (foo(a))[i] << endl;
     //does not work!! why?
        for(int i = 0; i < 10; i++) cout <<  a[i] << endl;
     return 0;
}
0
Comment
Question by:podoboq
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 15

Expert Comment

by:efn
ID: 8213967
In the first case, the foo function allocates an array and returns a pointer to it.  You can then subscript this returned pointer to read the elements of the array.

In the second case, the pointer a in main has a value of 0.  It doesn't point to any memory you can access, so you get an error when you try to read the memory to which it points.

The calls to foo(a) make a copy of the (zero) value of a in a temporary location for the use of the function.  The function stores a pointer to the newly allocated memory in this temporary location, but this has no effect on the a variable in main.  The a in foo is not the a in main, it is a copy of the value of a.

--efn
0
 

Accepted Solution

by:
violent1 earned 200 total points
ID: 8215968
your foo returns a pointer to an int.  in foo, you have created an array of ints, and you return a pointer to that array.  as said above, foo only gets a copy of a from main, not a itself...so, what you put into a in foo, isn't getting into the a in main.  this seems counter intuitive though, from what we learn about pointers.

but, what we did learn is that if we want to pass a variable and have any changes made to it from a function ACTUALLY occur to what we passed it, we pass it by reference.  great thing is, we can do that here.

simply adding one character to the parameter list of foo keeps your program from erroring:
int* foo(int* &a)

note the added "&"

*shrug*  sometimes things don't make sense...but hey...that's the fun in it all, lol


0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8216005
Or, to make it work, you can do:

a = foo ( a ) ;

You can also remove the parameter from the function altogether, and write: 'int * a = new int[10] ;' in the foo () function, and call it in main () as: 'a = foo () ;' and then print the values usig only your second 'for' loop.

Mayank.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:podoboq
ID: 8216162
that’s the point - i used to think that pointers are passed by reference. It’s arrays that made me think so. code like that is working fine:

void foo2(int a[], int n)
{
     for(int i = 0; i < n; a[i] = i++);
}

int main()
{
        const n = 3;
     int a[] = {1,2,3};
        for(int i = 0; i < n; i++) cout << a[i] << endl;    
        return 0;
}


now i got it -it's all about memory allocation -
"a" originally points to NULL, so any alterations to allocated by the copy of "a" memmory do not concern "a" itself.

anyway, rewriting  int* foo( int*& a) in plain C, we get int* foo(int** a), right?
(indeed adding & is much more simple, no code changes needed)

0
 

Author Comment

by:podoboq
ID: 8216172
sure, calling foo(a,n) first:)
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8216193
There is a difference between the two (passing a pointer by reference and passing a pointer by address). In the first case, its still a pointer variable which is formal argument and no text needs to be changed in the function. Also, the modifications made will be permanent and reflected in main (). In the second case, you are declaring another pointer in the foo () function, which is a pointer-to-a-pointer. Means that, it will hold the address of a pointer variable  itself. You'll have to call it as: 'foo (&a) ;' and make the function definition like:

void foo ( int ** p )
{
  * p = new int[10] ;
 
  for ( int i = 0 ; i < 10 ; i ++ )
    (*p)[i] = i ; // end for

} // end of foo ()

// Notice the parenthesis around *p. It is necessary otherwise *p[i] will be interpreted as *(p[i]) which is not what we want.

Mayank.
0
 
LVL 10

Expert Comment

by:substand
ID: 8216698
actually, by passing the pointer of a, it will still be able to change it.  

it is true that it "only makes a copy of a" but since a is a memory location, any changes you make to the mem location that a points to will be reflected in the main program.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8216720
>> any changes you make to the mem location that a points to will be reflected in the main program.

Yeah! Correct, but we're talking about making changes to the pointer 'a' itself, not the location where it originally pointed.

Mayank.
0
 
LVL 10

Expert Comment

by:substand
ID: 8216742
sorry, i must have read wrong =)
0
 

Author Comment

by:podoboq
ID: 8216950
well, thats all i wanted to know:))
thanks
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question