0

I'm trying to make a program where the user inputs the "shape" by adding characters such as *,/ etc. and then print it on the screen the amount of times the user inputs. The program works fine but in the end it says program not responding. Any help with that?

#include <iostream>
using namespace std;

int main()
{
    int a,h=1 ,b=0, x=7;
    char test[a][100];
    cout<<"Input how many lines ";
    cin>>a;
    cout<<"Input how many repeats ";
    cin>>b;
    for(int j=1; j<=a; j++)
    {
        cin>>test[j];
    }

    while(h<=b)
    {
        for(int c=1; c<=a; c++)
        {
            cout<<test[c]<<"\n";
        }
        h++;
    }
    return 0;
 } 
gsamaras
  • 71,951
  • 46
  • 188
  • 305
TheNewbie
  • 27
  • 2
  • 2
    `int a; char test[a][100];` - Ignoring that fact that variable-length arrays are not in the standard C++, it doesn't do what you think it does. The size of `test` doesn't become magically connected with the variable `a`. Rather, when you declare `test`, the size of `test` becomes equal to some random that happened to be in `a`, and doesn't change after that. Also, array indices start from `0`, so `for(int j=1; j<=a; j++)` has to be `for(int j=0; j – HolyBlackCat Jul 16 '18 at 08:41
  • did you try debugging? – Alan Birtles Jul 16 '18 at 08:41

1 Answers1

3

Your code invokes Undefined Behaviour (UB) here:

int a, ...;
char test[a][100];

You are trying to declare a fixed-size 2D array with an uninitialized variable (a).

Moreover, even if it was, variable-sized arrays are not standard C++.

If you enable the warning flags (such as Wall in GCC), you should get:

prog.cc:7:21: warning: 'a' is used uninitialized in this function [-Wuninitialized]
     char test[a][100];
                     ^

Moreover, array indexing starts from 0 and ends at the N - 1, where N is the size of the array. So you need to change this:

for(int j=1; j<=a; j++)

to this:

for(int j=0; j<a; j++)

in order to access the array right, and not out bounds as it happens when j gets the value of a. Accessing an array out of bounds causes Undefined Behaviour as well.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • What about when using like 7 lines, it crashes still. – TheNewbie Jul 16 '18 at 08:46
  • @TheNewbie [yes](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces). Make sure you understood my answer though, and work again on your code. I think that you should accept my answer now, trying working out your code, and then if you have more problems, ask a *new* question in Stack Overflow. Welcome! – gsamaras Jul 16 '18 at 08:48