简体   繁体   中英

how to take multiple strings as input and store them in a 2d array using c?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM