Arshitha
Arshitha

Reputation: 33

declaring empty string variable in c

#include <stdio.h>

int main() {
    char prompt1[] = "Enter your first name:", prompt2[] = "Enter your last name:";
    char gratis[] = "Thanks!", first[], last[]; //empty declaration of string varible 

    printf(prompt1);
    scanf("%s", &first);
    printf(prompt2);
    scanf("%s", &last);

    printf("%s\n", gratis);
    printf("Your name is %s %s\n", first, last);
    return (0);
}

Why can't the string variable be declared without specifying the size of the char array? The same code works fine when the size of the array is mentioned.

screenshot of the error

Upvotes: 1

Views: 2957

Answers (3)

M.M
M.M

Reputation: 141544

Arrays in C must have their size known when they are created, and the size cannot be changed after that.

So you must specify a size for all of your arrays.

You can omit the size number only if you provide an initializer, because the compiler can calculate the size from the initializer.

In your code you should select a size that is large enough to store what you expect. Also you used the wrong arguments to scanf. The code could be:

char first[100] = { 0 };    // avoid garbage in case input fails
scanf("%99s", first);

If you want to allow input of arbitrary size then you have to use dynamic allocation of space.

Upvotes: 1

Shadowmak
Shadowmak

Reputation: 111

When you create array like this it is allocated to the stack and therefore you need to specify the size of it in the declaration. On the other hand you can use pointer and allocate the size of the array later:

The array in C is basically a pointer to the first element of the array.

You can create empty array declaring

char *first;

after that you can define the array using

first = malloc(sizeof(char)*(SIZE_OF_ARRAY+1));

+1 because you need to put ending \0 character at the end of the string.

Then you can work with it the same as with the array itself.

Upvotes: -1

Daniel Jour
Daniel Jour

Reputation: 16156

In order for first and last to be usable in your context they need to have a complete type, that is a type whose size is known at compile time.

Thus you can either manually specify the array dimension (first[20]), or let the compiler deduce the dimension from an initialiser expression (like you did with prompt1 etc).

If you don't want to specify a dimension at compile time, then you need to switch to dynamically allocated memory using malloc and friends.

Note that you should also protect yourself from buffer overflows: scanf as used in your code will read an unknown amount of chars into the buffer you provide, making an overflow possible. See here for a discussion on how to avoid that.

Upvotes: 1

Related Questions