简体   繁体   中英

printing string from the array

as you can see this while I run this it works perfectly till "The array is " but cant show the string that I enter

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
    int size;
    char arr[size];
    printf("input size of array ");
    scanf("%d", &size);
    printf("\ninput elements of array  ");

    for (int i = 0; i < size; i++)
    {
        scanf("%s", &arr[i]);
    }

    printf("\nThe array  is ");

    for (int i = 0; i < size; i++)
    {
        printf("%s\n", arr[i]);
    }
    return 0;
}

There are multiple things wrong with this code.

int size;
char arr[size];

You are declaring a char array arr with size elements, but size is not yet initialized yet and may be any value. Also note that "deciding the size of an array at runtime" is only valid in modern C (C99 onwards). You should first read size and only after the scanf declare arr .

for (int i = 0; i < size; i++){
    scanf("%s", &arr[i]);
}

You read a string ( %s ) with scanf and try to store it in a char ( &arr[i] points to the ith char in arr ). Every C string is atleast 1 character long (the terminating \0 character), you are trying to store multiple characters in a single char . Instead use

scanf("%s", arr);

Note that scanf is not safe. Even if you enter more than size characters, it will still try to store them in arr . That leads to undefined behaviour, because arr is too small. Instead you can use fgets , that lets you set the number of characters to read.

for (int i = 0; i < size; i++){
    printf("%s\n", arr[i]);
}

Here you are trying to print a String ( %s ), but you are passing a char ( arr[i] is the ith char in arr ). Instead use

printf("%s\n", arr);

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