c - Alternative way to pass a char pointer to a function -
given source code strcpy()
char * strcpy(char *s1, const char *s2) { char *s = s1; while ((*s++ = *s2++) != 0); return (s1); }
why handing on second argument work , how in memory since not pass pointer function
char dest[100]; strcpy(dest, "helloworld");
in c string literals have types of character arrays. c standard (6.4.5 string literals)
6 in translation phase 7, byte or code of value 0 appended each multibyte character sequence results string literal or literals.78) the multibyte character sequence used initialize array of static storage duration , length sufficient contain sequence. character string literals, array elements have type char, , initialized individual bytes of multibyte character sequence.
also arrays rare exceptions converted pointers in expressions. c standard, 6.3.2.1 lvalues, arrays, , function designators
3 except when operand of sizeof operator or unary & operator, or string literal used initialize array, expression has type ‘‘array of type’’ converted expression type ‘‘pointer type’’ points initial element of array object , not lvalue. if array object has register storage class, behavior undefined.
thus in call
strcpy(dest, "helloworld");
the string literal has type char[11]
converted value of type char *
equal address of first character of string literal.
you write example
strcpy(dest, &"helloworld"[0]);
or :)
strcpy(dest, &0["helloworld"]);
or:)
strcpy(dest, &*"helloworld");
all 3 expressions yield address of initial element of string literal , have type char *
. take account implementation-defined (usually controlled compiler options) whether
"helloworld" == "helloworld"
is evaluated true. whether compiler allocates separate extents of memory identical string literals or store 1 copy of them.
in expression addresses of first characters of string literals compared.
if write
strcmp( "helloworld", "helloworld" )
then result equal 0 string literals equal each other (contain same sequence of characters)
Comments
Post a Comment