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:)

3
  • 2
    Hint: an array of length 4 cannot hold a string of length 4, the space for nul-terminator is not there. Commented Jun 29, 2020 at 15:18
  • Also, beware while using array as strings, they need null-termination to work. Commented Jun 29, 2020 at 15:20
  • scanf(" %[^\n]",a[i]); is worse than gets(). Commented Jun 29, 2020 at 15:53

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

and the outer dimension can very well stay as n.
@RohanBari, then better to delete these comments. Mine already erased.

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.