+ 1
How can I itterate through a 2d array in C given as a pointer?
So I have a function like this: int *func(int *arr, size_t n); Where *arr is the 2d array and n is the size of the array. The array is a square, so n is both width and height. I tried doing this: int val = arr[x][y]; But it gave me an error saying the subscripted value is neither array nor vector. Does someone know what I can do?
2 Antworten
+ 2
You can do it in multiple different ways. One would be to cast the array first:
int** nArr = (int**)arr;
Int val = nArr[x][y];
An array, even a 2d array ist consecutive in memory, so you can also:
int val = *(nArr+(n*x)+y);
+ 1
You can use a loop like
for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
printf("%d ", *(*(arr+i) + j) );
printf("\n");
}
edit:
ChrisVIN