Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 0.97 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to use array of pointers?
  2. #include<stdlib.h>
  3. #include<conio.h>
  4. int main(void)
  5. {
  6.     int rows=5,cols = 5;
  7.     int *a[100];
  8.     int i = 0;
  9.     int j;
  10.     int k = 0;
  11.     int b[100];
  12.     while(i<rows)
  13.     {
  14.         printf("nEnter the %d row: ",i);
  15.         for(j=0;j<cols;j++)
  16.             scanf("%d",&b[j]);
  17.  
  18.         a[k++] = b;
  19.         i = i + 1;
  20.     }
  21.     k = k-1;
  22.     for(i=0;i<=k;i++){
  23.         for(j=0;j<cols;j++){
  24.             printf("%d  ",a[i][j]);
  25.         }
  26.     }              
  27.  
  28.     getch();
  29.     return 0;
  30. }
  31.        
  32. a[k++] = b;
  33.        
  34. // int b[100]; // Delete this!
  35. while(i<rows)
  36. {
  37.     int *b = calloc(cols, sizeof(int)); // Replacement for int b[100]
  38.     printf("nEnter the %d row: ",i);
  39.     for(j=0;j<cols;j++)
  40.         scanf("%d",&b[j]);
  41.  
  42.     a[k++] = b; // Now it's safe to do this, because `b` is a different array each time
  43.     i = i + 1;
  44. }
  45.        
  46. int rows = 5, cols = 5;
  47. int** a;
  48. int i;
  49.  
  50. a = malloc(rows * sizeof(*a));
  51. for(i = 0; i < rows; i++)
  52.     a[i] = malloc(cols * sizeof(**a));