Reputation: 221
I'm going through K&R and it says array name is not a variable and it cannot be used in constructions like a=pa or a++.
Isn't s
an array name here?
#include<stdio.h>
main(){
printf("%d", strlen("test"));
}
int strlen(char s[])
{
int n;
for (n = 0; *s!= '\0';s++) // why is s++ valid even though it is declared as an array
n++;
return n;
}
Upvotes: 2
Views: 585
Reputation: 123598
From the horse's mouth:
6.3.2.1 Lvalues, arrays, and function designators
...
3 Except when it is the operand of thesizeof
operator, the_Alignof
operator, or the unary&
operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object hasregister
storage class, the behavior is undefined.
The expression "test"
is a string literal, which has type "5-element array of char
". When you pass "test"
as a parameter of strlen
, by the rule above, what actually gets passed is a pointer whose value is the address of the first character in "test"
.
Which brings us to...
6.7.6.3 Function declarators (including prototypes)
...
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. If the keywordstatic
also appears within the[
and]
of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.
So in the prototype for strlen
, char s[]
is equivalent to char *s
; s
is declared as a pointer to char
, not an array of char
.
C's treatment of arrays is a bit baroque compared to other languages. That's due in part to the BCPL and B heritage. If you're curious as to why, you can read dmr's The Development of the C Language for some insights.
Upvotes: 3
Reputation: 138
When Char s[]={...} is declared address is attached to s, which never changes (like constant pointer) and anything try to change this property becomes an illegal operation such as s++.
But In function call int strlen(char s[]) , array is passed as pointer.
Upvotes: 1
Reputation: 11
No, acctually s
is a pointer name.
The declaration int strlen(char s[])
is same as int strlen(char *s)
Upvotes: 1
Reputation: 182754
No, in this context it's a pointer to a char
. Your function declaration is completely equivalent to:
int strlen(char *s)
As you'll see, it's actually impossible to pass an array to a function: a pointer to the first element is what is actually passed.
Thus, since s
is actually a pointer and not an array, you're free to modify it as you please.
Upvotes: 3