Search code examples
arrayscscanfsizeof

Getting inputs with scanf for an array


Just getting to learn C better and I'm playing with arrays.

I would like to enter my phone number into an array like this:

#include <stdio.h>

int main() 
{

    int phoneNum[10];
    
    for (int i = 0; i < sizeof(phoneNum); i++) {
        printf("Insert digit %d of your phone number: \n", i + 1);
        scanf("%d", &phoneNum[i]);
    }

    return 0;
}

This seems to fail as it keeps asking me for a new digit. So I tried to print the size of the array:

int phoneNum[10];
printf("%lu", sizeof(phoneNum));

which incredibly gives me the result of 40 even though I initialized it to be 10 (?). I have three questions:

  1. Why is the result 40 and not 10 in sizeof(phoneNum) ?
  2. How can I add elements in an array successfully with scanf in the above manner?
  3. If the above manner is silly, is there a better, more efficient way to do this? For example directly enter 10 digits into an array? I can of course use scanf("%d%d%d...", digit1, digit2, digit3, ...) but I would like a generalized way, using the size of the array (say I don't know it and it's passed from another function)

Solution

    • sizeof(phoneNum) returns 10 * sizeof(int). The sizeof(int) value appears to be 4 for your system.

      #include <stdio.h>   
      
      int main() 
      {    
      
       int phoneNum[10] = {0};
       const size_t size = sizeof(phoneNum) / sizeof(int);
      
       for (int i = 0; i < size; i++) {
           printf("Insert digit %d of your phone number: \n", i + 1);
           scanf("%d", &phoneNum[i]);
       }
      
       for(int i = 0; i < size; ++i)
       {
           printf("\r\n %i \n", phoneNum[i]);
       }
       return 0;
      }