Home > Blockchain >  I'm not able to read my matrix dynamically
I'm not able to read my matrix dynamically

Time:12-12

My program crashes when it comes to the reading function, at the scanf line. What can I do?

I'm guessing it's an issue with the way I wrote (*(a i) j) but I can't tell.

void read(int **a, int n)
{
    int i, j;
    for(i=0;i<n;i  )
        for (j = 0; j < n; j  )
        {
            printf("a[%d][%d]=", i, j);
            scanf("%d", (*(a   i)   j)); //Access violation writing location 
        }
}

void show(int**a, int n)
{
    int i, j;
    for (i = 0; i < n; i  )
        for (j = 0; j < n; j  )
        {
            printf("%d", *(*(a   i)   j));
        }
}


int main()
{
    int n,opt,a;
    printf("number of lines and columns:");
    scanf("%d", &n);
    a = (int**)malloc(n*n * sizeof(int));
    while (1)
    {...

CodePudding user response:

A dynamic 2D n x n array is allocated using this code:

int (*a)[n] = malloc(n * sizeof *a);

It means: Declare a as pointer to an integer array with n element and allocate n of those arrays (i.e. n * sizeof *a). In that way it ends up with n x n integers.

So a full version of your code could be like:

#include <stdio.h>
#include <stdlib.h>

void read(int n, int a[][n])
{
    int i, j;
    for(i=0;i<n;i  )
        for (j = 0; j < n; j  )
        {
            printf("a[%d][%d]=\n", i, j);
            scanf("%d", &a[i][j]);
        }

}
void show(int n, int a[][n])
{
    int i, j;
    for (i = 0; i < n; i  )
    {
        for (j = 0; j < n; j  )
        {
            printf("%d ", a[i][j]);
        }
        puts("");
    }
}


int main(void)
{
    int n = 0;
    printf("number of lines and columns:\n");
    scanf("%d", &n);
    if (n < 1) exit(1);
    int (*a)[n] = malloc(n * sizeof *a);
    read(n, a);
    show(n, a);
    free(a);
    return 0;
}

note : To keep it simple I skipped all check of scanf return values. In real code, the scanf return value shall always be checked.

CodePudding user response:

There is nothing wrong with allocating a block using malloc ( n * n * sizeof *a);
The address of the block must be assigned to a pointer int *a
Elements can be accessed by (a i * n j) or a[i * n j]

void read(int *a, int n)
{
    int i, j;
    for(i=0;i<n;i  )
        for (j = 0; j < n; j  )
        {
            printf("a[%d][%d]=", i, j);
            scanf("%d", (a   i * n   j));
            // scanf("%d", &a[i * n   j]);
        }
}

void show(int *a, int n)
{
    int i, j;
    for (i = 0; i < n; i  )
        for (j = 0; j < n; j  )
        {
            printf("%d", *(a   i * n   j));
            // printf("%d", a[i * n   j]);
        }
}


int main()
{
    int n = 0, opt = 0, *a = NULL;
    printf("number of lines and columns:");
    scanf("%d", &n);
    a = malloc ( n * n * sizeof *a);
    while (1)
    {...
  •  Tags:  
  • c
  • Related