Why does scanf() need & operator (address-of) in some cases, and not others?

后端 未结 5 1790
情深已故
情深已故 2020-11-28 13:29

Why do we need to put a & operator in scanf() for storing values in an integer array but not while storing a string in a char array?

         


        
相关标签:
5条回答
  • 2020-11-28 13:36

    scanf accepts a pointer to whatever you are putting the value in. In the first instance, you are passing a reference to the specific int at position i in your integer array. In the second instance you are passing the entire array in to scanf. In C, arrays an pointers are synonymous and can be used interchangeably (sort of). The variable s is actually a pointer to memory that has contiguous space for 5 characters.

    0 讨论(0)
  • 2020-11-28 13:41

    scanf("%d", a + i ) works too.

    %d and %s just tell scanf what to expect but in both cases it expects an address

    in C, arrays and pointers are related.

    %s just says to scanf to expect a string which is \0 terminated, whether it will fit into the character array or not scanf doesn't care.

    0 讨论(0)
  • 2020-11-28 13:42
    • All the variables used to recieve values through scanf() must be passed by their addresses. This means that all arguments must be pointed to the variables used as arguments.

      scanf("%d", &count);

    • Stings are read into character arrays, and the array name without any index is the address of the first element of the array.So to read a string into a character array address, we use

      scanf("%s",address);

    • In this case address is already a pointer and need not to be preceded by the & operator.

    0 讨论(0)
  • 2020-11-28 13:43

    When you use the name of an array in an expression (except as the operand of sizeof or the address-of operator &), it will evaluate to the address of the first item in that array -- i.e., a pointer value. That means no & is needed to get the address.

    When you use an int (or short, long, char, float, double, etc.) in an expression (again, except as the operand of sizeof or &) it evaluates to the value of that object. To get the address (i.e., a pointer value) you need to use the & to take the address.

    0 讨论(0)
  • 2020-11-28 13:51

    Because characters arrays are already pointers.

    You can think of C arrays as pointers to a stack-allocated amount of RAM. You can even use pointer operations on them instead of array indexing. *a and a[0] both produce the same result (returning the first character in the array).

    0 讨论(0)
提交回复
热议问题