TheNewbie
TheNewbie

Reputation: 27

Sample program crashes

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

Upvotes: 0

Views: 52

Answers (1)

gsamaras
gsamaras

Reputation: 73366

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.

Upvotes: 3

Related Questions