Stamatis Tzanos
Stamatis Tzanos

Reputation: 93

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)

Upvotes: 0

Views: 175

Answers (2)

I NN_
I NN_

Reputation: 185

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.

Upvotes: 0

embeddedstack
embeddedstack

Reputation: 387

  • 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;
    }
    

Upvotes: 3

Related Questions