c - why a pointer can be assigned value? -
i have puzzle here:
int *a=*b; a[1]=3; a[2]=5
a pointer array , assigned value b. in understanding, a[]should address, why in practice can assign value place pointer (in case a[]) to? explain?
i'm assuming c, or c subset of objective c/c++, since c+, java, php, , other c-like languages don't use pointers.
use code tags , single statement per line.
the statement
int *a = *b;
creates pointer int. not pointer pointer int, pointer int.
it sets current address in a dereference of b, whatever b is. did not show declaration of b. unless b of type int **
, should getting compiler warning.
a not pointer array. pointer int. point single int, or made point array of ints. compiler can't tell difference..
if b of type int **
, or pointer pointer int, statement dereferences 1 of pointers , makes point first sub-array inside b.
the code
a[1] = 3;
assumes pointer array of integers, , since compiler can't range checking, tries index array , save value second int in block of memory points to. if not point block of memory large enough contain @ least 2 integers, statement may crash on modern computer using protected memory, might overwrite memory follows.
as @eds. points out in comment below, known in business
"undefined behavior"
if you're going use c pointer this, burden on make sure points valid memory, , if you're going use pointer if it's array, burden on make sure don't exceed bounds of memory pointed pointer.
Comments
Post a Comment