I'm trying to access 1D array as 2D array. But it falls into Segv. Below is snippet the i had written. Can anyone please take a look into this?
void printarray(int **a){
printf("#####2D access... \n");
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
printf("## %u-->%d \n", &a[i][j],a[i][j]);
}
}
}
int main(){
int a[4] = {10,20,30,40};
printf("%u %u %u \n", &a, a, &a[0]);
printf("%u %u %u %u \n", &a[0], &a[1], &a[2], &a[3], &a[4]);
printarray((int **)a);
return 0;
}
And vice-versa(Accessing 2D array as 1D array) situation is simply handled by type casting.Below is the snippet and this works fine.
void printarray(int *a){
printf("#####1D access... \n");
for(int i=0;i<4;i++){
printf("## %u-->%d \n", &a[i],a[i]);
}
}
int main(){
int a[2][2] = {
{10,20},{30,40}
};
printf("%u %u %u %u \n", &a, a, a[0], &a[0]);
printf("%u %u \n", a[0], &a[0]);
printf("%u %u \n", a[1], &a[1]);
printarray((int *)a);
return 0;
}
thanks, Hari
a**is an pointer to a pointer. Not a two dimensional array.a[i][j]is probably trying to usea[i]as a pointer and then getting thejthelement after that pointer. It is(a[i])[j]so a[0][1] is going to be((int*)(10))[1];on a 32 bit system.