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.

1
  • 1
    @Kerrek_SB It's not the same question. Commented Nov 26, 2013 at 13:54

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

5 Comments

int array[][n] is an array of pointers to int where int **array is a pointer to pointer to int. Is that right?
@rullof int array[][n] is an array of/a pointer to an undefined amount of arrays of n ints (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 ints).
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
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.”
This is wrong. Eric Postpischil is right. array is int *
-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;

1 Comment

The statements in this answer are about declarations within a block. The question is about function parameters, which behave differently.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.