stack
stack

Reputation: 414

When to use & when reading an input

I'm quite confused regarding the scanf() . When do we use & when we read data from the keyboard. To my understanding, & is always used when you want the program to read in something.

Eg. scanf("%c",&varA) or  scanf("%d",&varA)

I also understand that when you use a pointer, you don't use & for scanf().

What about if I want to scanf() something into an array? do I use a &? I know that the name of an array evaluate to the address of the first element of an array, which is also something like a pointer.

Upvotes: 1

Views: 48

Answers (3)

Haris
Haris

Reputation: 12270

scanf() uses format string, so to read for a particular variable one needs to see which would give the address of the variable


1) For a normal variable int a, & is needed, scanf("%d", &a);

2) For a pointer variable int* a, no & is needed, scanf("%d", a);

3) For an array int a[10],

  • While using the name only, no & is required, scanf("%s", a);
  • While using for an element, & is required, scanf("%d", &a[0]);

Upvotes: 3

Sufian Latif
Sufian Latif

Reputation: 13356

The parameters passed to scanf after the first one are all addresses. You need to provide the address of the variable to assign the value of the input.

That's why, when you read the value of a variable, you have to pass its address using the & operator.

For example,

int n;
scanf("%d", &n);

You can also assign the variable's address address to a pointer and use that:

int n;
int *p = &n;
scanf("%d", p);

In case of arrays, the array's name is actually the base address, i.e. address of the first element. You can use that in scanf too:

int arr[4];
scanf("%d", arr); // the input value will be stored in a[0]
scanf("%d", &arr[0]); // does the exactly same thing as the statement above

scanf("%d", &arr[1]); // reads the input into a[1]
scanf("%d", a + 1); // does the same as above

This way is useful for reading strings without spaces from input:

char str[64];
scanf("%s", str);

Upvotes: 3

tdao
tdao

Reputation: 17668

What about if I want to scanf() something into an array?

It depends on what array you are interested in.

  • If it's a character array, then you can use scanf("%s", s); without & operator (given s is the char array).
  • If it's numeric array, then you will need to scanf("%d", &a[i]); for individual array element, thus you will need the & operator.

Upvotes: 0

Related Questions