c - Why assignment to a subscripted array works and assignment to a dereferenced pointer arithmetic expression - doesn't? -
kernighan & ritchie 2nd ed. says:
the correspondence between indexing , pointer arithmetic close. definition, value of variable or expression of type array address of element 0 of array. after assignment
pa = &a[0];
pa
,a
have identical values. since name of array synonym location of initial element, assignmentpa=&a[0]
can written as
pa = a;
rather more surprising, @ least @ first sight, fact reference
a[i]
can written*(a+i).
in evaluatinga[i]
, c convertsa[i]
immediately; 2 forms equivalent. applying operator & both parts of equivalence, followsand
identical:a+i
address ofi
-th element beyond a. other side of coin, ifpa
pointer, expressions may use subscript;pa[i]
identical*(pa+i)
. in short, an array-and-index expression equivalent 1 written pointer , offset.
and after reading this, expect 2 programs work identically:
/* program 1 */ #include <stdio.h> int main() { char arr[] = "hello"; arr[0] = 'h'; printf("%s\n", arr); } /* program 2 */ #include <stdio.h> int main() { char *arr = "hello"; arr[0] = 'h'; printf("%s\n", arr); }
but first 1 works. second 1 segmentation fault.
why? reference authoritative source appreciated.
when define , initialize array, of array allocated in modifiable memory (usually stack), , can modify array way want.
when use string literal, compiler give pointer read-only zero-terminated array of char
. attempting modify array (which in second example) leads undefined behavior.
Comments
Post a Comment