Reputation: 30699
I've got some code I'm mantaining with the following variable declaration:
char tmpry[40];
It's being used with this function:
char *SomeFunction(char *tmpryP) {
// Do stuff.
}
The function call is:
SomeFunction(&tmpry[0]);
I'm pretty damn sure that's just the same as:
SomeFunction(tmpry);
I've even checked that the char* pointer in SomeFunction ends up pointing to the same memory location as the array in both cases.
My question is a sanity check as to whether the two function calls are identical (and therefore the original programmer was just being nasty)?
Upvotes: 7
Views: 24386
Reputation: 5169
The C Programming FAQ section on arrays and pointers tackles this (and many other common C questions and confusions.
Upvotes: 5
Reputation: 2053
The declaration
int a[10]; int *pa;
There is one difference between an array and a pointer that must be kept in mind. A pointer is a variable, so pa=a and pa++ are legal. But an array name is not a variable; construction like a=pa and a++ are illegal
As format parameters in a function definition, char s[] and char *s are equivalent;
From: The C Programming Language 2th, Page 99-100
Upvotes: 1
Reputation: 84822
It may be significant, if SomeFunction
is a macro and takes "sizeof"
of one of its arguments, because sizeof(tmpry)
may not necessarily be equal to sizeof(&tmpry[0])
.
Otherwise, as others pointed out, they are exactly the same.
Upvotes: 7
Reputation: 753725
As everyone else said, the two notations are equivalent.
I would normally use the simpler one, unless there are multiple calls like this:
SomeFunction(&tmparry[0]);
SomeFunction(&tmparry[10]);
SomeFunction(&tmparry[NNN]);
Where ideally all the constants (magic numbers) would be enum (or #define
) constants.
Upvotes: 3
Reputation: 6604
they are exactly the same.
someArray[i]
means exactly
*(someArray + i)
where someArray in the second case is a pointer to the memory location. Similarly,
&someArray[i]
means exactly
(someArray + i)
In both these cases the terms are pointers to memory locations.
Upvotes: 12
Reputation: 170499
These two variants are equivalent and passing like this
SomeFunction(tmpry);
looks cleaner.
Upvotes: 1
Reputation: 73443
Both are one and the same although second one looks nice and clarifies the intention of passing the array to the function. But how does the SomeFunction know the size of the array being passed, is it always assumed as 40 ? I feel it is better to pass the size also as the parameter to SomeFunction.
Upvotes: 1
Reputation: 21620
The two are equivalent and I think SomeFunction(tmpry); is more readable.
Upvotes: 12