2

Possible Duplicate:
Should I use char** argv or char* argv[] in C?

What is the difference between using char **argv and char *argv[] for the second parameter to a c program. Does it affect the way the strings are passed? Thanks :-)

Community
  • 1
  • 1
rubixibuc
  • 7,111
  • 18
  • 59
  • 98
  • I don't qualify this as an 'answer', so I'll put it here, but I do feel that this is important. You will find that people have problems reading this one way or the other, between being stubborn and being ignorant. If you work for someone and you're told to do it a particular way, don't ever forget it or you may have a fine time trying to fix all of those. :P. – Zéychin Jul 07 '11 at 20:30
  • Arrays decay to pointers, so there is no difference between the two. – Marlon Jul 07 '11 at 20:53

3 Answers3

7

There is absolutely no difference. At all.

in C

void f(int*);

and

void f(int[]);

and

void f(int[42]);

are three completely identical declarations.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
4

**argv and *argv[] as a function argument are technically identical - as C will convert any array into a pointer in a function argument.

Note that this can catch you out, for example this is totally valid and won't raise any warnings (or errors), even though a beginner might think that the array passed is invalid:

void func(int array[2])
{
    array[1] = 1; // buffer overrun: will write past the end of a[].
}

int main()
{
    int a[1];
    func(a);
    return 0;
}
DaveR
  • 9,540
  • 3
  • 39
  • 58
2

In the context of a function parameter declaration, T a[] and T *a are synonymous. In both cases, a is a pointer to T.

When an array expression appears in a context other than as an operand to the sizeof or unary & operators (such as a parameter in a function call), the type of the expression is implicitly converted from "N-element array of T" to "pointer to T", and the value of the expression is the address of the first element in the array. Thus, a function can never receive an array value; it can only receive a pointer to the first element.

dmr decided to use the T a[] syntax to make the intent clear (a refers to the first element of an array of T as opposed to a pointer to a single instance of T), but I think it's caused more heartburn that it was worth.

John Bode
  • 119,563
  • 19
  • 122
  • 198