0

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;
}
  • 1
    Couple of issues: `char arr[size];` is a 1d array that can hold a single c-string. Also, `size` is uninitialized at that point so even when you change `size` later, the array is already created. – 001 May 01 '21 at 17:43
  • 1
    To fix: _first_ get `size` from the user, then declare: `char arr[size][100];`. Also, you can change to `scanf("%s", arr[i]);`...*You can change `100` to the max string length you expect. – 001 May 01 '21 at 17:51
  • Sidenote: VLAs can be tricky to use. If the user enters a very large value for `size` you can overwrite the stack. Dynamic memory allocation (`malloc`) might be better here. [Is it required that a C Variable Length Array is allocated from the stack?](https://stackoverflow.com/a/33020514) – 001 May 01 '21 at 17:54

1 Answers1

1

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);
lulle2007200
  • 888
  • 9
  • 20