-4

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.

8
  • 1
    what is your question? Commented Dec 17, 2019 at 14:52
  • 2
    std::vector Commented Dec 17, 2019 at 14:52
  • Although more than likely they wont let you use that and you need something like: stackoverflow.com/questions/1350630/… Commented Dec 17, 2019 at 14:54
  • My question is if there any ways of taking an unknown amount of inputs without declaring the size of the array Commented Dec 17, 2019 at 14:55
  • Can you explain what the assignment allows you to use? Can you use standard library containers? Can you use pointers? Can you use the new and delete keywords? What operating system are you using? What IDE and compiler are you using? Commented Dec 17, 2019 at 15:00

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
  }
}

1 Comment

You should describe what the program is doing for the answer to be useful - but I think the "we aren't allowed to utilize pointer" comment makes this approach problematic anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.