-1
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i,j;
    int (*a)[3]=NULL;
    for(i=0; i<4;i++)
    {
      for(j=0; j<3;j++)
      {
        scanf("%d", *(a+i)+j);
      }
    }
    for(i=0; i<4;i++)
      for(j=0; j<3;j++)
        printf("%5d", a[i][j]);
    printf("\n");
    return 0;
}

I have a problem with my C code above, which is trying to print a multi-dimensional array on screen. When running this code, a message of segmentation fault is sent to me and I don't know how to fix that.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ghostio
  • 1
  • 1
  • 3
    You have a null pointer in `a` — you try to index it. That leads to crashes. You need to allocate the space for your '2D array' `a` before you use it. – Jonathan Leffler Apr 02 '22 at 17:46
  • Note that your printing will put the entire array on a single line. You probably need `{` after the first of the `for` loops and `}` after the `printf("\n");` line. And revised indentation, – Jonathan Leffler Apr 02 '22 at 17:56
  • The 'obvious' fix is `int a[4][3];`. – Jonathan Leffler Apr 02 '22 at 17:57
  • Yeah but I'm practicing to use pointer – ghostio Apr 02 '22 at 18:00
  • OK; then the first rule of using pointers is "make sure the pointer points at real storage before you try using it to access the storage". So, you need to allocate memory for your array. There are many ways to do that. You should show what you think should work after proving that it doesn't. (If it does work, you don't have a question.) – Jonathan Leffler Apr 02 '22 at 18:04

1 Answers1

1

The segmentation fault is due to the null pointer int (*a)[3]=NULL.

Either: allocate it dynamically (in this case, you have to free it when done with it):

int (*a)[3] = malloc(sizeof *a * 4);

or declare it static:

int a[4][3];

Also, you are missing some curly braces:

for(i=0; i<4;i++) { // This one
    for(j=0; j<3;j++)
        printf("%5d", a[i][j]);
    printf("\n");
} // And this one
Zakk
  • 1,935
  • 1
  • 6
  • 17