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:
- Why is the result 40 and not 10 in
sizeof(phoneNum)
? - How can I add elements in an array successfully with
scanf
in the above manner? - 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)