Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is size of an array flexible in C++?

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!

like image 463
Harish Avatar asked Dec 23 '22 17:12

Harish


2 Answers

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);
like image 184
bhristov Avatar answered Dec 25 '22 06:12

bhristov


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).

like image 27
Rohan Bari Avatar answered Dec 25 '22 06:12

Rohan Bari