-5

I found the following sample code, demonstrating the use of sscanf() on TutorialPoints:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   strcpy( dtm, "Saturday March 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s\n", month, day, year, weekday );

   return(0);
}

I'm confused about the use of the ampersand in &day, &year. From what I've read, the ampersand is used in this manner on a pointer variable in order to say "don't change where the pointer is pointing to but rather change the value at the address the pointer is already pointing to".

Here it's funny though, because day and year are not pointers. They are just simple ints. Why can't it be written as:

...
 sscanf( dtm, "%s %s %d  %d", weekday, month, day, year );
...

?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • 6
    time to read a basic C tutorial... – Mitch Wheat Dec 12 '13 at 11:54
  • Hint: What are the arguments for `scanf`? – devnull Dec 12 '13 at 11:55
  • Because without the `&`s they're pass-by-value. Scanf needs to write to them, so it needs a reference to them that it can write to i.e. a pointer. – Rup Dec 12 '13 at 11:56
  • And this bit sounds wrong: "From what I've read, the ampersand is used in this manner on a pointer variable in order to say "don't change where the pointer is pointing to but rather change the value at the address the pointer is already pointing to". No: the value at the address is `*pointer`. `&pointer` is a pointer-to-a-pointer. – Rup Dec 12 '13 at 11:57

4 Answers4

2

The ampersand means "address of". So what you're doing in sscanf is providing addresses in which to store the scanned data: weekday and month are strings, so a reference to weekday rather than *weekday is just using the address rather than the value. Since day and year are ints rather than int*s, you need to use the ampersand to provide the address.

The data type of &day is int*.

benwad
  • 6,414
  • 10
  • 59
  • 93
1

you misunderstand. & gets the address of something, i.e. &date returns a pointer to date.

Oliver Matthews
  • 7,497
  • 3
  • 33
  • 36
1

In this example you are passing the address of the variable to the function. In this way the function is able to modify the content of the variable.

In particular, sscanf, parses the string in input and writes a value to the indicated address.

HAL9000
  • 3,562
  • 3
  • 25
  • 47
0

In above case Day and Year are values, so its required & for storing value, but week and month's are address (i.e weekday == weekday[0]) so & symbol not required.