Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ampersand or no ampersand before string variable name in scanf() and printf()?

The compiler I'm using is Dev C++ 5.11. TDM-GCC 4.9.2 32-bit Debug. C99 mode.

1.

 char str1[100], str2[100];
 scanf("%s %s", &str1, &str2);
 printf("%s %s", &str1, &str2);

2.

 char str1[100], str2[100];
 scanf("%s %s", &str1, &str2);
 printf("%s %s", str1, str2);

3.

 char str1[100], str2[100];
 scanf("%s %s", str1, str2);
 printf("%s %s", str1, str2);

Every code works. Why? I'm very confused.


1 Answers

The first thing you need to remember is that arrays naturally decays to pointers to their first element. That is, in your example str1 and &str1[0] are equal.

The second thing to remember is that a pointer to an array, and a pointer to its first element will point to the same location, but they are semantically different since they are different types. Again taking your array str1 as example: When you do &str1 you get something of type char (*)[100], while plain str1 (or its equivalent &str[0]) you get something of type char *. Those are very different types.

Last thing you need to remember is that both scanf and printf when reading/printing strings take a pointer to a char (i.e. char *). See e.g. this scanf (and family) and this printf (and family) references for details.

All that means is that only alternative 3 in your question is the correct one.

like image 198
Some programmer dude Avatar answered Dec 13 '25 21:12

Some programmer dude