c - Pointers pre/post increment -


can please explain following code completely?

#include<stdio.h> #include<stdlib.h>  int main() {     int *a, *s, i;      = s = (int *) malloc(4 * sizeof(int));      (i = 0; < 4; i++)     {         *(a + i) = * 10;         printf(" %d ", *(a + i));     }      printf("\n");     printf("%d\n", *s++);     printf("%d\n", (*s)++);     printf("%d\n", *s);     printf("%d\n", *++s);     printf("%d\n", ++*s);     printf("\n");     printf("%d\n", *a++);     printf("%d\n", (*a)++);     printf("%d\n", *a);     printf("%d\n", *++a);     printf("%d\n", ++*a);      return 0; } 

output:

0 10 20 30 0 10 11 20 21  0  11 12 21 22 

1) how pointer 's' printing values, *(a+i) been assigned values in loop?

2) value go , stored when *(a+i) assigned?

3) what's difference between *s++, (*s)++, *++s, ++*s ?

4) why values incremented 1 when print pointer similar s?

thanks in advance ! :)

1 , 2) pointer points (or can address of) memory location. since assign a = s = (int*) malloc(4 * sizeof(int));, a , s both has same address, or points same memory location. if changes content @ memory location (e.g. in code, assigning numbers allocated memory), long have right address (both a , s points same location), can see content changes.

a rough analogy that, ask house (malloc), , gives address of house (a). decide house ugly, , want re-paint (assign value: *(a + i) = + 10), other people told address (s) see house has been repainted.

3)

*s++ means access content @ current address, , later increments pointer (address).

reflect code, accesses first element, address point second element.

(*s)++ means access content @ current address, , later increments content @ current address.

reflect code, gets content of second element before incrementing it. next print statement shows content of second element having been incremented.

*++s means increments current address, , access content @ incremented address.

reflect code, gets content of third element.

++*s means increments content @ current address, , access incremented content.

reflect code, gets incremented content of third element.

4) explained in earlier part, if modify content via 1 pointer, see if have same pointer (address). modifying content of memory addresses (as explained in 3), may see effect of modification when repeat process.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -