Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf a string in a char pointer [duplicate]

Tags:

c

pointers

scanf

I want to scan a string and point a char pointer to this scanned string.

int main(int argc, char *argv[]) {

    char *string;
    scanf("%s",&string);
    printf("%s\n",string);

}

But gives a warning saying

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **'

How do I scan a string in a char * without warnings.

Edit : It worked for the below code with warnings and I drilled down it to the above one so to be very specific.

int main(int argc, char *argv[]) {

    int n = 2;

    char *strings[2];
    for(int i = 0; i < n; i++){
        scanf("%s",&strings[i]);
        printf("%s\n",&strings[i]);
    }

}

enter image description here

like image 315
BangOperator Avatar asked Jun 20 '16 11:06

BangOperator


1 Answers

First of all, %s in scanf() expects a pointer to char, not a pointer to pointer to char.

Quoting C11, chapter §7.21.6.2 / p12, fscanf() (emphasis mine)

s
Matches a sequence of non-white-space characters.286)

If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. [...]

Change

scanf("%s",&string);

to

scanf("%s",string);

That said, you need to allocate memory to string before you actually try to scan into it. Otherwise, you'll end up using uninitialized pointer which invokes undefined behavior.

like image 179
Sourav Ghosh Avatar answered Oct 16 '22 06:10

Sourav Ghosh