After declaring a character array, say char s[20]
, and eventually getting inputs using cin.getline(s,100)
change the size of the array to 100, change (exactly) to the number of characters entered as input, or does it change at all? What happens to the array size that I initially declared?
I'm new to programming, so your simple explanation will be greatly appreciated. Thank you!
The size does not change what happens is that you are writing past the buffer size. If you write far enough through the buffer you will end up causing a buffer overflow.
You should use std::vector
whenever you can instead of c-style arrays.
As Ted Lyngmo commented, in this case std::string
will be better to use than std::vector or the c-style array:
std::string input;
std::getline(std::cin, input);
The answer is: No.
The size of the character array s
doesn't changes to 100
, but when you exceed the limit of the array's length, you cause a buffer overflow, which is really bad.
Let's consider an incorrect program, which is based on your assumption:
#include <iostream>
int main(void) {
char s[20];
std::cout << "Enter a sentence: ";
std::cin.getline(s, 100);
std::cout << s << std::endl;
return 0;
}
Here I just try to expand the size of array s
, it actually doesn't.
If you enter an example sentence, like: hello-world-how-are-you-today
(which contains 29
characters including a null-terminator), it'll just store:
hello-world-how-are-
And notice that it doesn't contains a null-terminator
since all the containers are used and it just keeps reading which may cause undefined behavior (UB).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With