C Variables and Pointers -


refering https://stackoverflow.com/a/22250138/5783540 says:

when have

int = 10; 

and

&a 

it turns out is: int*

but why pointer? know &a give memory address doesn't hold address number 10 or wrong?

please read: know pointer is, know & does. i'm confused with:

to address of a, do: &a (address of a) returns int* (pointer int) 

again, why should int a pointer?

edit: guys. reading wrong. there no hidden magic behind pointers. bad reading...

the former answer correct, think doesn't solve doubts.
on typical system have memory done of array of cells able hold values. each cell accessed cpu issuing on bus address of required cell.
when declare variable compiler reserves area in memory chunk allocated process.
on cpu can access variable through address. on only way access variable using address.
when refer variable compiler automatically use address address correct memory location, loads value cpu register operate on it.
there many cases need address of variable not value.
i.e. if want modify variable defined in caller function:

void bar(int *pointer) {     *pointer = 1; } void foo(void) {     int = 0;     bar(&a);     printf("a modified in bar() %d\n", a); } 

in variable holds memory address of variable of type called pointer type.
why pointer of pointer of pointer.... ?
example:

void bar(int **pointer) {     **pointer = 1; } void foo(int **a) {     bar(a);     printf("a modified in bar() %d\n", *a); } 

of course there more useful use of ;-)
following more realistic example, call function dynamically creates array.

void bar(int **pointer, int nelems) {     //we got address of variable pointer int     //note use single dereference access     //variable holds pointer int not pointed int.     *pointer = malloc(sizeof(int) *nelems) ; } void foo(void) {     int *myintarray;    //holds address our array starts     bar(&myintarray, 10);   //pass address of our variable                             //bar() can update allocated address     int i;     for(int i=0; i<10; i++)         myintarray[i] = i+1;      for(int i=0; i<10; i++)         printf("myintarray[%d] = %d\n", i, myintarray[i]);      free(myintarray); } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -