Advertisement
abs25

C pointers

Aug 14th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. //http://www.programiz.com/c-programming/c-pointers
  2. #include <stdio.h>
  3. int main(){
  4.     //Ampressed used to give memory location aka container where value from scanf should be saved
  5.     //scanf("%d", &var);
  6.  
  7.     //pointers are used to store memory locations of other variables and make them accessible
  8.     //if we stored memory locations in integers there would be no way to access them,
  9.  
  10.     //int *pc; same as int* pc;
  11.     int *pc;
  12.     int c;
  13.     c = 22;
  14.     printf("Address of c:              &c = %d\n", &c);
  15.     printf("Value of c:                 c = %d\n\n", c);
  16.     pc = &c;
  17.     printf("pc = &c\n\n");
  18.     printf("Address of pointer pc:     pc = %d\n", pc);
  19.     printf("Content of pointer pc:    *pc = %d\n\n", *pc);
  20.     c = 11;
  21.     printf("c = 11\n\n");
  22.     printf("Address of pointer pc:     pc = %d\n", pc);
  23.     printf("Content of pointer pc:    *pc = %d\n\n", *pc);
  24.     *pc = 2;
  25.     printf("*pc = 2\n\n");
  26.     printf("Address of c:              &c = %d\n", &c);
  27.     printf("Value of c:                 c = %d\n\n", c);
  28.  
  29.     printf("=====================================\n\n");
  30.  
  31.     /* an array with 5 elements */
  32.     double balance[5] = { 1000.0, 2.0, 3.4, 17.0, 50.0 };
  33.     double *p;
  34.     int i;
  35.     // array variable name without index is same as refference to first element (&balance[0])
  36.     p = balance;
  37.  
  38.     /* output each array element's value */
  39.     printf("Array values using indexes\n");
  40.     for (i = 0; i < 5; i++) {
  41.         printf("p[%d]: %f\n", i, p[i]);
  42.     }
  43.  
  44.     printf("Array values using pointer\n");
  45.     for (i = 0; i < 5; i++) {
  46.         printf("*(p + %d) : %f\n", i, *(p + i));
  47.     }
  48.  
  49.     printf("Array values using balance as address\n");
  50.     for (i = 0; i < 5; i++) {
  51.         printf("*(balance + %d) : %f\n", i, *(balance + i));
  52.     }
  53.  
  54.     printf("%d\n", sizeof(double));
  55.  
  56.     for (i = 0; i < 5; i++) {
  57.         printf("&balance[%d] = %d\n", i, &balance[i]);
  58.     }
  59.  
  60.     for (i = 0; i < 5; i++) {
  61.         printf("*(balance + i) = *(%d + %d) = *(%d) = %f\n", balance, i, (balance + i), *(balance + i));
  62.     }
  63.  
  64.  
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement