0

My first post here. Programming in C. Sorry if this has been answered before, as I wasn't sure how to search for it. I'm wondering why I needed to put a & operator when scanning for an int, but not for a char array. My guess is that it has something to do with storing the int inside the address, as opposed to inside the array, but I don't fully understand.

Here's my code:

#include <stdio.h>

int main(void) {

  char user_word[10];

  printf("enter a word: ");

  scanf("%s", user_word);

  printf("%s\n", user_word);

  int user_num;
  
  printf("enter a number: ");

  scanf("%d", &user_num);

  printf("%d\n", user_num);

}

Also, please let me know if I have any bad coding conventions in how it was typed.

Thanks :)

Sasha
  • 827
  • 1
  • 9
  • 16
sparky
  • 1

1 Answers1

3

The scanf function expects a pointer. The & operator gets the address of a variable. When passed to a function, any array (including char arrays) decays to a pointer to its first element, so the & operator is unnecessary.

This can be seen in the below very simple program that prints an array of ints.

#include <stdio.h>

void print(int *arr, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        printf("%d\n", arr[i]);
    }
}

int main(void) {
    int arr[] = {1, 2, 3, 4, 6, 7, 8, 9};

    print(arr, 8);

    return 0;
}

The print function expects an array of ints. The array arr is passed in and decays to a pointer to the first element.

Chris
  • 26,361
  • 5
  • 21
  • 42