Arman Akbarian
UNIVERSITY OF BRITISH COLUMBIA
PHYSICS & ASTRONOMY DEPT.

/* AAK:
 * This is an example code to learn 
 * array/matrices and pointer handling in C
 * memory allocation etc..
 * last update:
 * Sat Sep 15 17:10:05 PDT 2012
 */

#include <stdio.h>


int main(int argc, char *argv[]) {

   double *p;
   int *q;
   double r;
   int y[3][3]; /* Two dimensional arrays are pointer to pointers */
        int x[10]; /* in C arrays are basically pointers */
   int i,j;

   r = 10.0;
   p = &r;
   *p = 5.0;
   printf("Value of r changed to = %f\n",r);

   for(i=0;i<10;i++){
      x[i] = 2 * (i+1);
   }

   /* q will be a pointer to first element in array x */
   q = x;
   printf("First element in x = %d\n",*q);

   /* going to the neighbooring memory position using pointer: */
   printf("4th element in x = %d\n",*(q+3));
   /* or equivalently */
        printf("4th element of x = %d\n",q[3]);

   /* allocating memory of 5 double variable and returning
    * the address to p 
    * */

   p = (double *)malloc(sizeof(double)*5);

   /* malloc(N) allocates N bytes
    * sizeof(type) returns the number of bytes for that type of data
    */

   printf("Values in p: %f %f %f %f %f\n",p[0],p[1],p[2],p[3],p[4]);

   q = (int *)malloc(sizeof(int)*10);

   /* making q shifted compared to x */

   q = &(x[1]);

   printf("q is shifted by one as you can see:\n");
   printf("q's = %d %d %d %d ...\n",q[0],q[1],q[2],q[3]);
   printf("x's = %d %d %d %d ...\n",x[0],x[1],x[2],x[3]);

   /* The following line basically "copies" the vector x into q */

   q = x;

   printf("q and x are the same: %d = %d , %d = %d \n",q[9],x[9], q[5],x[5]);

   /* Higher dimensional arrays are also stored in a continuous memory
    * with first index runs first, see the output: 
    * Note that two dimensional array is a pointer to pointer*/

   for(i=0;i<3;i++) {
      for (j=0;j<3;j++){
         y[i][j] = 10*(i+1) + j + 1;
      }
   }

   for(i=0;i<3;i++){
      printf("y[%d][1],y[%d][2],y[%d][3] = %d %d %d\n",i,i,i,y[i][0], y[i][1], y[i][2]);
   }


   printf("Y's are stored as:\n");
   for(i=0;i<3;i++) {
      for (j=0;j<3;j++){
         printf(" %d ",*(*(y+j)+i));
      }
   }
   printf("\n");


/* Strings in C are handled by pointers to character */
char *str;

  str=(char *)malloc(sizeof(char)*10);
  printf("Enter an string:\n");
  scanf("%s",str);
  printf("You entered: [%s]\n",str);
  str="Hi!  ";
  printf("str changed to: [%s]\n",str);

/* or you can define str as char str[10] */

}


last update: Wed May 11, 2016