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, assignment pa=&a[0] can written as
pa = a;

rather more surprising, @ least @ first sight, fact reference a[i] can written *(a+i). in evaluating a[i], c converts a[i] immediately; 2 forms equivalent. applying operator & both parts of equivalence, follows and identical: a+i address of i-th element beyond a. other side of coin, if pa 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

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -