0

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)
3
  • 1
    Check this link out : stackoverflow.com/questions/37538/… Commented Nov 4, 2022 at 11:29
  • Any particular reason you're failing to check the return value from scanf() to be sure it actually reads data before you loop to the next element? Commented Nov 4, 2022 at 11:39
  • @AndrewHenle I simply desire to understand this between arrays. The optimization part is another journey which is irrelevant for this topic. Commented Nov 4, 2022 at 13:07

2 Answers 2

3
  • 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;
    }
    
Sign up to request clarification or add additional context in comments.

Comments

0

sizeof(phoneNum) will return number in bytes, not length of array.
after the includes you could make a define like #define SIZE 10 and use SIZE like if it was a constant.

#include <stdio.h>
#define SIZE 10

int main()
{
    int phoneNum[SIZE];

    for (int i = 0; i < SIZE; i++)
    {
        //Do Something
    }
}

Take into account the fact that strings should end with null terminated character (\0) so the size of the string have that space available.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.