Why is ampersand used in front of these variables?

1.1k views Asked by At

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 );
...

?

4

There are 4 answers

0
Oliver Matthews On

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

0
HAL9000 On

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.

0
benwad On

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*.

0
Lingesh Nagarajan On

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.