Shury
Shury

Reputation: 578

Read string C - Linux

I'm trying to read a string and print it in Linux using:

cc child.c -o child

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

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

    char st[100];

    scanf("%s", &st);
    printf("%s", st);

    return 0;
}

However I encounter this warning that will not allow me to compile.

child.c: In function ‘main’:
child.c:8:2: warning: format ‘%s’ expects argument of type ‘char ’, but argument 2 has type ‘char ()[100]’ [-Wformat=] scanf("%s", &st);

How can I solve it? Thanks!

Upvotes: 1

Views: 1800

Answers (2)

haccks
haccks

Reputation: 105992

In C, when passed to a function, array names converted to pointer to the first element of array. No need to place & before st. Change

scanf("%s", &st);  

to

scanf("%s", st);

Upvotes: 4

datenwolf
datenwolf

Reputation: 162164

In C array types degenerate to pointers. So when you take the address of an array, you actually get a pointer to a pointer. Just pass the array itself to scanf.

Upvotes: 2

Related Questions