views:

117

answers:

4

Hi,

what is the difference between following function declarations, which create and return the array in C/C++? Both methods create the array and fill it with proper values and returns true if everything passed.

bool getArray(int* array);
bool getArray(int* array[]);

Thanks

Best Regards, STeN

+3  A: 

If it helps you to think about it you can remember that int foo[] is the same thing as int *foo at one level. So in your example the first is passed a pointer to an int while the second is passed a pointer to a pointer to an int.

Ukko
Just to clarify: `int foo[]` and `int *foo` are equivalent *in the context of function parameters*.
jamesdlin
Hi,Thanks - this really help solving my problem. I am normally using only C++ or Objective-C with special container classes for everything and each time I am doing th pure C I fall in troublesfor few days until I get on the right path:((The right questing should be: What is the difference between<code>bool getArray(int** array);</code> and<code>bool getArray(int* array[]);</code>I think (hopefully correctly) there there is no difference...Thanks all you guys for help.Regards
STeN
+1  A: 

bool getArray(int *array); takes a pointer to an int as an argument (effectively an array of ints to fill). bool getArray(int *array[]);takes an array of int pointers. The first one is the one you want, though the caller will need to allocate a sufficiently large output array so getArray() can copy the array elements into it.

One way to understand C pointer/array declarations is to think of them as illustrating how to access the base type. int *array means that if you say *array, you'll get an int. int *array[] means if you say *array[x], you'll get an int. char (*array)[5][2][3] means if you say (*array)[0 thru 4][0 thru 1][0 thru 2], you'll get a char.

Joey Adams
If I were doing it, I'd probably do `int *getArray()` ;-)
Joey Adams
A: 

The second requires a pointer to an array. So if you the array is int *getme; then you call getArray(&getme);

Duracell
No, the second requires an array of pointers. A pointer to an array would be `int (*array)[]`.
Joey Adams
Oops, that's right. Sorry, missed that one.
Duracell
+1  A: 

On a side note, the code you posted is C++. There's no such thing as "C/C++"... What makes your prototypes recognizable as C++-conformant is the use of the data type "bool" for the functions' return types. Boolean variables aren't defined in C.

guidj0s
"bool" was added to C in C99, although you have to #include <stdbool.h> to get it.
Daniel Stutzbach