2

When defining a function like this:

void  myFunction(arguments){
   // some instructions
}

What is the deference between using type name[] and type *name as the function's argument.

When using type name[] and calling the function does it make a copy to the name array or just point to the passed array.

Is the name array's subscript needs to be set. If not what's the difference.

rullof
  • 7,124
  • 6
  • 27
  • 36

3 Answers3

2

There is no difference to my knowledge which is actually a problem in this situation:

int func(int a[20]) {
    sizeof(a); // equals sizeof(int*)!!
}

Therefore I always prefer the pointer form, as the array form can cause subtle confusion.

djechlin
  • 59,258
  • 35
  • 162
  • 290
1

Either way only a pointer is passed.

void f(int array[]);

is synonymous to passing a const pointer

void f( int * const array);

They become non-synonymous when passing two dimensional arrays with bounds

void f(int array[][n]);

is synonymous to

void f(int (* const array)[n]);

But different to

void f(int **array);
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • `int array[][n]` is an array of pointers to int where `int **array` is a pointer to pointer to int. Is that right? – rullof Nov 26 '13 at 14:14
  • @rullof `int array[][n]` is an array of/a pointer to an undefined amount of arrays of `n` `int`s (single block of memory). While `int ** array` is an array of pointers to `int` (each of which can point to it's own separate block of memory holding an undefined amount of `int`s). – Sergey L. Nov 26 '13 at 14:17
  • For the first one you'r right just it's an undefined amount of int not array of int. the second one (int **array) i don't think so, it's just a pointer to pointer to int. `array` is just the name otherwise you means something else – rullof Nov 26 '13 at 14:23
  • 5
    An `int array[]` parameter is **not** adjusted to `int * const array`. It is just `int *array`; there is no `const`. If the parameter were `int array[const]`, then it would be adjusted to `int * const array`. Per C 2011 (N1570) 6.7.6.3 7: “A declaration of a parameter as ‘‘array of *type*’’ shall be adjusted to ‘‘qualified pointer to *type*’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.” – Eric Postpischil Nov 26 '13 at 14:59
  • 1
    This is wrong. Eric Postpischil is right. `array` is `int *` – newacct Nov 26 '13 at 22:44
-2

In C++ it's the same. Different is in declaration;

char *s = "String"; // allocated and fill
char str[80];      // allocated memory
char *p1;          // not allocated memory
p1 = str;
Nix
  • 1
  • The statements in this answer are about declarations within a block. The question is about function parameters, which behave differently. – Eric Postpischil Nov 26 '13 at 15:01