Sudarshan
Sudarshan

Reputation: 96

Input matrix in C using function

I am trying to input a matrix of order p*q using a function I got some errors. how to get the input using a pointer it gives me a segmentation fault .

#include<stdio.h>

int read_matrix(int *x,int p,int q){
    for(int i=0;i<p;i++){
        for(int j=0;j<q;j++){
            scanf("%d",*(x+i)+j);
        }
    }
    return 0;
}

int main(){
    int p,q;
    printf("enter the order of the matrix");
    scanf("%d%d",&p,&q);
    int a[p][q];
    read_matrix(a[q],p,q);
    for(int i=0;i<p;i++){
        for(int j=0;j<q;j++)
            printf("%d",a[i][j]);
    }
}

Upvotes: 0

Views: 196

Answers (2)

Lundin
Lundin

Reputation: 215360

You are making things needlessly complicated with the pointer arithmetic. *(x+i)+j means x[i] + j*sizeof(int) which is not what you want.

Just do something like this instead:

#include<stdio.h>

void read_matrix(int x, int y, int matrix[x][y])
{
  int count=0;
  for(int i=0;i<x;i++)
    for(int j=0;j<y;j++)
      matrix[i][j] = ++count;
}

int main (void)
{
  int x=3, y=2;
  int matrix[x][y];

  read_matrix(x,y,matrix);

  for(int i=0;i<x;i++)
  {
    for(int j=0;j<y;j++)
      printf("%d ",matrix[i][j]);
    printf("\n");
  }
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409482

You have multiple problems and seem to misunderstand how arrays and pointers work. To begin with a[q] will be out of bounds if p <= q.

a[q] (if q is valid) is an array of q elements, which decays to a pointer to its first element. It's not any kind of pointer to the matrix itself.

And inside the read_matrix function when you do *(x + i) + j that is actually equal to x[i] + j which is a single int value, and not a pointer to an element in any array.

You need to pass the matrix itself to the function, and let it decay to a pointer to an array, and use that as a proper "array of arrays":

// Use variable-length arrays for the matrix argument x
// Declare it as a pointer to an array of q integer elements
// Note the changed order of arguments, it's needed because q must be declared
// before its used for the VLA
void read_matrix(int p, int q, int (*x)[q]) {
    for (int i = 0; i < p; ++i) {
        for (int j = 0; j < q; ++j) {
            scanf("%d", &x[i][j]);  // Use normal array indexing and address-of operator
        }
    }
}

int main(void) {
    int p, q;
    scanf("%d %d", &p, &q);

    int a[p][q];

    // Here a will decay to a pointer to its first element, &a[0]
    // Since a[0] is an array of q elements, the type will be
    // int (*)[q], exactly as expected by the function
    read_matrix(p, q, a);

    for (int i = 0; i < p; ++i) {
        for (int j = 0; j < q; ++j) {
            printf("%d ", x[i][j]);
        }
        printf("\n");
    }
}

Upvotes: 3

Related Questions