During my high school c++ course we were assigned an assignment to write a program that allows the user to input values that would be stored in an array without prompting the user for the array size. So if the user decides to enter 1,2,3 the array size would go from being unknown to three.
2 Answers
the array size would go from being unknown to three.
It is not possible to change the size of an array, nor is it possible to create an array of unknown size.
However, if the array is allocated dynamically then what you can do is allocate another, bigger array and copy elements of the smaller array onto the bigger one. Such data structure is called a "resizable array". The standard library has a container that implements such data structure: std::vector. You can use it to implement your program.
Comments
use std::vector if you're allowed to, otherwise something like this might help
#include <cstdlib>
#include <iostream>
template <typename T>
struct list final {
T* values;
std::size_t capacity, size;
list() : values{nullptr}, capacity{0u}, size{0u} {}
~list() { std::free(values); }
void push_back(T value) {
if (size == capacity) {
capacity = (capacity + 1) * 2;
if (void* mem = std::realloc(values, capacity * sizeof(T))) {
values = reinterpret_cast<T*>(mem);
} else {
throw std::bad_alloc();
}
}
values[size++] = value;
}
void pop_back() { --size; }
};
int main() {
list<int> integers;
for (int i = 0; i < 10; ++i) {
integers.push_back(i);
}
for (int i = 0; i < integers.size; ++i) {
std::cout << integers.values[i] << std::endl;
}
}
std::vector