I'm trying to pass in an array into a function. But what is the difference between
Code:void function(int *array) void function(int *&array)
I'm trying to pass in an array into a function. But what is the difference between
Code:void function(int *array) void function(int *&array)
This passes a pointer to an array of integers. Usually reflects a numerical or character value...in this case numerical.Code:void function(int *arrray)
This passes the address reserved in memory of the array.Code:void function(int *&array)
Knowledge is power and I want it all
-0RealityFusion0-
so regardless of which i use, it is the same right?
Depends on how you use it. If you are wanting to use a specific element of the array in the function then you would use the int *array. Your best bet would be to try it both ways. If you get some odd value like 0xffff8763f then you are getting the address.
Knowledge is power and I want it all
-0RealityFusion0-
well, if you want to change where a pointer points, you will want to pass a reference to it...
Code:void myfunc(int *arr) { arr = NULL; } int *arr = new int[5]; myfunc(arr); arr still is valid, not null.Code:void myfunc(int *&arr) { arr = NULL; } int arr = new int[5]; myfunc(arr); arr is now NULL.
No, they're not quite the same. When you use arrays, the compiler reserves some amount of space, the beginning of which has the address &A[0](A being an array of course). When you pass an array into a function, your program passes not the array, but the beginning address of the array. The second example you'll use less often. When the need for modifying a pointer in function occurs you either pass in a pointer to a pointer or you pass a reference to a pointer. The syntax isn't that clear, so you might rewriteso regardless of which i use, it is the same right?
Code:typedef Node* NodePtr; void f(NodePtr& p)] { p = 0; }
the first is passing by value. the second is passing by reference.
its the same as(but with pointers instead)....
void func (int); // by value
void func (int&); // by reference
Theres some more info about this in the FAQ. Look at the pointer tuts.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
Initially I got confused by a book which states that array is always pass by reference. Now I understand what is going on. Thanks guys for your help!
rockytriton explanation is pretty good!