user5084667
user5084667

Reputation:

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.

Upvotes: 3

Views: 1207

Answers (4)

kocica
kocica

Reputation: 6465

In C, any expression of array type is implicitly converted to a pointer to the array's first element unless it has reference operator.

scanf("%s %s", &str1, &str2);

is

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

and the address of the array is always the same as the address of the first element.

Upvotes: 1

0___________
0___________

Reputation: 68034

Because it string is an array of the char. So address of the array is the address oh it's first element.

They just have different types.

Upvotes: 0

Lundin
Lundin

Reputation: 215235

  • str1 gives a char pointer char* to the first element, which will be allocated at the first address in the array.
  • &str1 gives an array pointer to the array as whole, of type char(*)[100].
  • The address of the array is always the same as the address of the first element.
  • By using the %s format specifier you tell printf to treat the passed pointer as a char*. So no matter which pointer type you pass, it will get converted to this type.
  • As it happens, this particular pointer conversion from char(*)[100] to char* has to yield the very same address, so the code works no matter which pointer type you use.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409472

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.

Upvotes: 5

Related Questions