The Question asks the User to input a 2D array whose no. of rows are fixed (take rows = 3) and no. of columns are given by the User as follows:
Input:
2 1 2
4 10 20 30 40
5 6 7 8 9 0
Here in the first line 2 1 2
, first input tells about the no. of columns in the row index [0] and rest of input are values for row index [0]. And so on for the rest of the lines.
Then, the User enters the row and column index and prints the respective value.
Input: 1 2
Output: 30
I solved it using the array of pointers as:
#include <stdio.h>
int main()
{
int a, c;
int x , y; // index coordinates
int *pa[3];
pa[0] = &a;
for (int i = 0; i < 3; i++)
{
if(i != 0)
pa[i] = pa[i-1] + c; //point to mem address c*sizeof(int) bytes away from prev pointer
scanf("%d", &c); //input no. of column for row[i]
for (int j = 0; j < c; j++)
{
int k;
scanf("%d", &k);
*(pa[i] + j) = k;
}
}
scanf("%d %d", &x, &y);
printf("--> %d", *(pa[x] + y));
return 0;
This runs correctly on MSVC and Clang but for some reason not on GCC. There is some kind of run-time error during Input in GCC.
PS: I have solved this using dynamic mem allocation but just wanted to know why the above code does not work in case of GCC:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **data = (int **) malloc(3*sizeof(int*));
for(int i = 0; i < 3; ++i)
{
int c;
scanf("%d", &c);
data[i] = (int *) malloc(c*sizeof(int));
for(int j = 0; j < c; ++j)
{
int k;
scanf("%d", &k);
data[i][j] = k;
}
}
int i, j;
scanf("%d %d", &i, &j);
printf("--> %d", data[i][j]);
for(int i = 0; i < 3; ++i)
free(data[i]);
free(data);
return 0;
}