Aryaman Todkar
Aryaman Todkar

Reputation: 19

data type(char) in C

If input is given a big number like 344565786464675345 still I get output how is this possible as char has range 256 so it should not take numbers greater than that, why char can store such big integers?

int main()
{
    char b[30];
    scanf("%s",b);
    printf("\n%s",b);
    return 0;
}

Upvotes: 0

Views: 103

Answers (3)

sjsam
sjsam

Reputation: 21965

char b[30];

b is an array and you can store up to 30 characters.

As a response to

scanf("%s",b);

You have entered 18 characters

344565786464675345 

A null character \0 has been appended to what you have entered because of the %s specifier which makes a total of 19 characters. Or

b[18]='\0' // Remember the count starts from 0

So you still have 11 free bytes in your array b as a character is 1 byte.

Mind that if you're trying store a string in the array, then the array to be null terminated, ie you need to have a \0 at the end of a character array for the group to be considered a string.

So, technically you can have a string of up to 29 characters using char b[30] for it to make a valid string.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

There is a difference between a char and an array of chars, which is what you have.

An array is capable of storing up to 29 digits plus null terminator, but the value that you enter is not stored as a large integer. Instead, it is stored as a sequence of characters, where each character represents a single digit:

Index of b[]  0   1   2   3   4   5   6   7   8  ...
char value   '3' '4' '4' '5' '6' '5' '7' '8' '6' ...
num value     51  52  52  53  52  53  54  55  54 ...

All characters have numeric values in the range that can be represented by a single char.

Upvotes: 2

ameyCU
ameyCU

Reputation: 16607

What you have is array of 30 char and not a single char -

char b[30];   //b is an array of char 

So b's size is 30*sizeof(char) . It means it can hold 30 characters (including '\0') . Your input is stored in this character array (sufficient for input provided) and therefore, you can get correct output.

Upvotes: 1

Related Questions