HugoB - 9 months ago 54

C Question

I have to create a matrix and manipulate it with only one pointer

my code:

`#include <stdio.h>`

#include <time.h>

#include <stdlib.h>

void Matrix();

int Fun(int *A, int n, int key);

int main()

{

Matrix();

return 0;

}

void Matrix()

{

int Nel, Larray, i, j, k, a, c, b, Nf;

printf("Num of elements: ");

scanf("%d", &Nel);

int A[Nel][Nel];

srand(time(NULL));

for(b=0;b<Nel;b++)

{

for(c=0;c<Nel;c++)

{

A[b][c] = rand() % 100 + 1;

}

}

printf("\n");

for(b=0;b<Nel;b++)

{

for(c=0;c<Nel;c++)

{

printf("%d\t",A[b][c]);

}

printf("\n");

}

printf("\n\n");

printf("Num to find? ");

scanf("%d", &Nf);

Fun(*A, Nel, Nf);

}//end

int Fun(int *A, int n, int key)

{

//just to see if it works

int i,j;

for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

{

printf("%d\t",A);

}

printf("\n");

}

}

In the function Fun, gives me an error

`printf("%d\t",A); subscripted value is neither array nor pointer nor vector`

I have to use only one pointer to call the matrix.

Can you expalin the pointer arithmetic in multi dimensional array? Thx

Answer Source

Assuming you have `int* arr;`

pointing to an array of size `[ROWS_NUM][COLS_NUM]`

, the calculation done when trying to access `arr[X][Y]`

is `arr + (X * COLS_NUM + Y)`

.

A general rule would be that an absolute index of an element in a multi-dimensional array would be `absolute_index = ((index1 * size2 + index2) * size3 + index3) * size4 + index4 .....`

(to which you just add the offset of the array).

You can look at this sketch to understand the way a multi-dimensional array is formatted in memory: