0

The following is my code written in c language where I am trying to take strings as input and store them in a 2d array.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
    int i,j,n;
    scanf("%d",&n);
    char a[n][n];
    for(i=0;i<n;i++){
        scanf(" %[^\n]",a[i]);
    }
    for(i=0;i<n;i++){
        printf("%s\n",a[i]);
    }
}

below is my input
4
1112
1912
1892
1234

my excepted output should look like below
1112
1912
1892
1234

the output which I am getting is below
1112191218921234
191218921234
18921234
1234

can anyone explain what is wrong in my code? any help would be appreciated! thanks:)

AKSHAY KADAM
  • 129
  • 8

1 Answers1

1

You need to change:

char a[n][n];

Into:

char a[n][n + 1];

For a null-terminator. Without that, the char array won't be terminated and keep printing.

You'll get the correct output afterwards:

$ gcc -o prog prog.c; ./prog
4
1112
1912
1892
1234
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34