I'm doing some tests with a user inputting strings into my program through the command line, but I'm confused by something. When I specify the maximum size of a char[] array, the program is still somehow making the char[] longer than the max length I specified, with no errors.
Why is this the case? And why does sizeof(input)
show 5 bytes, despite input
containing 14 characters?
#define MAX_LENGTH 5
int main(){
char input[MAX_LENGTH];
printf("Max length: %d\n", MAX_LENGTH);
printf("strlen(input) = %d\n", strlen(input));
printf("sizeof(input) = %d\n", sizeof(input));
printf("Enter string: ");
scanf(" %s", input);
printf("strlen(input) = %d\n", strlen(input));
printf("sizeof(input) = %d\n", sizeof(input));
printf("Input: %s", input);
return 0;
}
I would expect this to either scan the first 5 characters of the user's input; but instead, it gives input the entirety of what is typed...?
cmd line output:
Max length: 5
strlen(input) = 0
sizeof(input) = 5
Enter string: foobarpizzapie
strlen(input) = 14
sizeof(input) = 5
Input: foobarpizzapie