1

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

1 Answer 1

1

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: enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

This is pretty clear, but how can I fix my problem? With 2 pointers I have no problem, but I have to use only one pointer!
Replace printf("%d\t",A) with printf ("%d\t",*(A+(i*n+j))) or with printf ("%d\t",A[i*n+j]) and mark answer as resolved if that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.