Pregunta

If we have the following code, the memory for variable b is not taken, when we call function f. But if the function f would have the prototype void f(int* &a) then the memory would be allocated. How is this possible?

#include <iostream>

using namespace std;


void f(int* a)
{
    a = new int[10];
    a[0] = 55;
}


int main()
{
    int *b;
    f(b);
    return 0;
}

EDIT: Well I got the main idea but why is still possible then?

void f(int a[])
{
     a[0] = 5;
}

int b[] = {1,2,3,4,5};
f(b);

//The value of b[0] will be 5 after the end of function call
¿Fue útil?

Solución

You are passing the pointer by value, so f has its own copy of it. The pointer a is local to f, so the caller has no access to it (and the memory allocated is leaked, BTW).

When you pass the pointer by reference, a is semantically the same pointer as was passed. So the pointer passed by the caller points to the memory allocated in the function.

Otros consejos

Pointer int * b; is actually a variable. A variable which hold an memory address of an integer. For example:

int n;
int* b = &n;     // pointer b is pointing to n

Since a pointer is a variable you can pass it by value or by reference. Here you pass it by value to the function. Check also the http://en.cppreference.com/w/cpp/language/pointer.

In the case of void f(int* &a) you pass by reference the int* a variable. It is a variable (that hold a memory address of a variable of type int) which it is not initialized to any value yet in your code (in main()).

In your second code. In the function void f(int a[]) when you pass int b[] = {1,2,3,4,5}; with f(b); you make "implicit" conversion of array name to a pointer. The problem is that the function f() does not know the size of the array. For example you use this calls in functions like strlen() where you pass null terminating strings. Check book "The C++ Programming Language", 3rd Edition by Bjarne Stroupstrup page 92.

There is also a basic rule: a[i] <=> (*(a+i)). So your function void f(int a[]) is equal with void f(int* a) definition. Check "Navigating C++ and Object-oriented Design" by Gail Anderson, page 40: http://books.google.gr/books?id=b-NiT6w8FTAC&pg=PA40#v=onepage&q&f=false

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top