
Untitled
By: a guest on
Jun 17th, 2012 | syntax:
None | size: 0.97 KB | hits: 18 | expires: Never
How to use array of pointers?
#include<stdlib.h>
#include<conio.h>
int main(void)
{
int rows=5,cols = 5;
int *a[100];
int i = 0;
int j;
int k = 0;
int b[100];
while(i<rows)
{
printf("nEnter the %d row: ",i);
for(j=0;j<cols;j++)
scanf("%d",&b[j]);
a[k++] = b;
i = i + 1;
}
k = k-1;
for(i=0;i<=k;i++){
for(j=0;j<cols;j++){
printf("%d ",a[i][j]);
}
}
getch();
return 0;
}
a[k++] = b;
// int b[100]; // Delete this!
while(i<rows)
{
int *b = calloc(cols, sizeof(int)); // Replacement for int b[100]
printf("nEnter the %d row: ",i);
for(j=0;j<cols;j++)
scanf("%d",&b[j]);
a[k++] = b; // Now it's safe to do this, because `b` is a different array each time
i = i + 1;
}
int rows = 5, cols = 5;
int** a;
int i;
a = malloc(rows * sizeof(*a));
for(i = 0; i < rows; i++)
a[i] = malloc(cols * sizeof(**a));