0

I've seen a question on this, but I am not really understanding it as I haven't learned pointers/memory in school, and this is an assignment for school. I'm trying to write a program that takes an integer value from the user, and prints out an upper right triangle with the same leg length. I'm using an array and then storing each cell with a character depending on its coordinates. It's running fine when I compile it, but it doesn't work on my submission. Can someone explain why I'm getting the error in the title?

    #include <iostream>
    #include <string>

    using namespace std;

    int main()
    {
        int size, m, n;
        cout << "Size";
        cin >> size;
        cout << endl;;
        const int ARRAY_SIZE = size;
        string tri_array[(ARRAY_SIZE)][(ARRAY_SIZE)];
        for(m = 0; m < size; m++)
        {
            for(n = 0; n < size; n++)
            {
                if(m > n)
                {
                    tri_array[m][n] = " ";
                }
                else
                {
                    tri_array[m][n] = "*";
                }
            }
        }
    return 0;
    }
user1529
  • 13
  • 3
  • 1
    Do you agree that that the length of your array is determined by the variable `size`? Do you understand from your error message that "C++ forbids" this? `std::vector` is the common array-like structure whose length can be determined at runtime. – Drew Dormann Sep 29 '22 at 19:55
  • 1
    [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Drew Dormann Sep 29 '22 at 19:59
  • 1
    ***I am not really understanding it as I haven't learned pointers/memory in school, and this is an assignment for school*** Use `std::vector` which is beginner friendly and save the advanced code (that uses new and pointers and manual memory management) for your later studies. – drescherjm Sep 29 '22 at 20:01
  • ... if your tutor will let you, some are a bit 'Jurassic' that way – Paul Sanders Sep 29 '22 at 21:29
  • Re your other question just asked and deleted, this is considered *very* rude. SO is not here to answer your specific questions, it's meant to provide a long-term repository of questions and answers for developers. Deleting a question after you have your answer totally negates the effort people have spent on helping both you and the wider community. – paxdiablo Oct 25 '22 at 00:04

1 Answers1

2

A variable length array is an array whose size is determined at run-time.

According to the C++ language, array sizes (capacities) must be determined at compile time.

In your code, the capacities are determined at run-time, thus violating the size constraint of an array.

Please switch to using std::vector, whose capacity can be set during run-time.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154