Is size of an array flexible in C++?

Viewed 285

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!

4 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);

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

C++ doesn't have a variable-length array.

To handle this situation, you can have below data structures.

Click on the links, and you will find the description and usages.

Arrays don't have dynamic memory. If you want dynamic memory allocation, you can use std::string for an array of characters, or std::vector.

std::string works like char s[x];, but it is more flexible and it has a few different things.

std::vector is basically like an array, but you can add / remove elements.

Syntax:

std::vector<type> name; // this is the classic syntax, I won't get more in-depth

Example:

std::vector<int> myVect;

You can add elements using myVect.insert(position, element); or something similar, I don't remember exactly, or you can use myVect.push_back(element); to add an element at the end of the vector.

Search it on cplusplus reference or GeeksForGeeks, you'll find a lot of information.

Related