0

When I use scanf for getting an integer I have to use the address operator &

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

However this does not work with scanning strings.

char word[256];
scanf("%s",word);

has to be used. It does not work when I use the & operator. Why is this.

Inian
  • 80,270
  • 14
  • 142
  • 161

5 Answers5

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

int main()
{
    char word[256];

    printf("%p \n", word);
    // 0x7ffeefbff450

    printf("%p \n", &word[0]);
    // 0x7ffeefbff450

    // Wrong
    printf("%p \n", &(&word[0]));
    // Meaningless to ask the address of an address

    return 0;
}

For a given array

char word[256]

The name word is equivalent to the address of the first element in the array

First element in array word is word[0], its address is &word[0]

word == &word[0] ----> &word == &(&word[0])----> Undefined 

& is applied only to variable name, not to variable address

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

number is not an array, so number is the name of a variable not an address

To get the address of the variable number, do &number

will &(&number) make sense to you?

Adam
  • 2,726
  • 1
  • 9
  • 22
1

& is used to get the address of the variable. C does not have a string type, String is just an array of characters and an array variable stores the address of the first index location. By default the variable itself points to the base address and therefore to access base address of string, there is no need of adding an extra &

source : geeksforgeeks

0

The name of an array represent the address of array in c.
In C string is array of characters so it by default giving address of string
In case of int we use & for address of variable

follow this link http://www.c4learn.com/c-programming/mcq/array-name-is-base-address/

rohit prakash
  • 565
  • 6
  • 12
0

because when we take input in an integer 'a', it is the name of the pocket generated and its address is something else. we need to point to that address where the input value should be stored.

& is the address operator in C, which tells the compiler to change the 
real value of this variable, stored at this address in the memory.

but in case of string / array of character, it already pointing to the first location.

so, you can get the value of its any pocket, it will add (size of its datatype * pocket id) like- str[4] we want to access then it will go to access to address of str + 1*4 and it will give 5th character of the string.

0

A String in C is basically a pointer to the first Entry of the char-Array, so by giving the function the string, you are already giving it a pointer wich it needs, if you do &String your trying to give it a pointer to the pointer to the Beginning of the String.