Declare an array inside if statement

Hi, I'm writing a program right now but, I'm stuck at declare a variable inside if statement. My code looks like this
1
2
3
4
5
6
7
8
9
10
11
12
  char x[6];
  Int y;
  for(;;){
  cin>>x;
  If(strcmpi(x,"input")==0){
  cin>>y;
  int z[y];
  Process(&z);
  }else if(strcmpi(x,"output")==0){
  output(z);
  }else return 0;
  }
closed account (j3Rz8vqX)
1
2
3
4
5
6
7
8
9
10
11
12
    char x[6];
    int y;
    for(;;){
        cin>>x;
        if(strcmpi(x,"input")==0){
            cin>>y;
            int z[y];                       //Not a c++ standard, use "int *z=new int[y];" or vectors.
            process(&z);
        }else if(strcmpi(x,"output")==0){
            output(z);                      //z not declared in this scope.
        }else return 0;
    }
Thanks for the answer, I'll try it later when my computer is on
int z[y]; Illegal in C++. Array size should be known in compile time.

Your z varuable will be only visible in then branch of if, and will be destroyed after line 8.

To make code compliant you can either use C++ containers (vector) or dynamic memory allocation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int* z = nullptr;
//..
//I assume, following in the loop of some kind
std::cin>>x;
if(strcmpi(x,"input")==0) {
    std::cin>>y;
    delete[] z; // if you decide to create new array
    z = new int[y];
    process(&z);
}else if(strcmpi(x,"output")==0) {
   output(z);
} else {
    delete[] z; //Cleanup
    return 0;
}


}
Maybe I'll really need to learn about vector. Oh yeah what if I need to declare more than 1 variable ?
Well, like in my code: you declare pointer somwhere else and then allocate memory for it:
1
2
3
4
5
6
7
8
9
10
11
12
13
int* x = nullptr;
int* y = nullptr;
bool b;
std::cin >> b;
if(b) {
    x = new int[5];
    y = new int[10];
} else {
    x = new int[10];
    y = new int[5];
}
delete[] x;
delete[] y;


With vectors:

1
2
3
4
5
6
7
8
9
10
11
std::vector<int> x;
std::vector<int> y;
bool b;
std::cin >> b;
if(b) {
    x.resize(5);
    y.resize(10);
} else {
    x.resize(10);
    y.resize(5);
}
Thanks for the answer i'll learn more about it
closed account (j3Rz8vqX)
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstring>
using namespace std;
void process(int *&data, int size)
{
    for(int i=0;i<size;++i)
    {
        cout<<"Number ["<<i<<"]: ";
        cin>>data[i];
        cin.clear();
        cin.ignore(1000,'\n');
    }
}
void output(int *data, int size)
{
    for(int i=0;i<size;++i)
        cout<<data[i]<<' ';
    cout<<'\n';
}
int main()
{
    char x[6];
    int y, *z;
    while(cout<<"Enter a string (input or output): "){
        cin.getline(x,7,'\n');
        if(strcmp(x,"input")==0){//strcmpi is non standard for c++
            cout<<"Enter a size: ";
            cin>>y;
            cin.clear();
            cin.ignore(1000,'\n');
            delete []z;
            z = new int[y];
            process(z,y);
        }else if(strcmp(x,"output")==0){//strcmpi is non standard for c++
            output(z,y);
        }else{
            delete []z;
            return 0;
        }
    }
}
Enter a string (input or output): input
Enter a size: 3
Number [0]: 5
Number [1]: 7
Number [2]: 2
Enter a string (input or output): output
5 7 2
Enter a string (input or output): exit

Process returned 0 (0x0)   execution time : 18.553 s
Press any key to continue.
Do you realize that your code can access the array out of bounds? You defined x with a size of 6 yet you allow the user to enter 7 characters into this array. Also remember this version of getline() will place the stream in an error state if the delimiter is not found before the specified size is reached.

Also why the character array in the first place, a std::string would much less error prone.
closed account (j3Rz8vqX)
Also why the character array in the first place, a std::string would much less error prone.
It was to correlate to the OP's program; I wanted to specifically demonstrate char array.

You defined x with a size of 6 yet you allow the user to enter 7 characters into this array.
True that greater validations were necessary, which I had neglected, but 7 or more would be the size you would want, definitely not 6. If you feel otherwise, try it.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
void test(char str[], int i)
{
    cout<<"Testing with "<<i<<" character delimiter: \n";
    cout<<"Enter the string (output): ";
    cin.getline(str,i,'\n');
    cout<<str<<'\n';
    if(cin.fail())
    {
        cin.clear();
        cin.ignore(1000,'\n');
    }
    cout<<'\n';
}
int main()
{
    char str[6];
    test(str,6);
    test(str,7);
    return 0;
}
Testing with 6 character delimiter:
Enter the string (output): output
outpu

Testing with 7 character delimiter:
Enter the string (output): output
output


Process returned 0 (0x0)   execution time : 10.006 s
Press any key to continue.
Extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character).
True that greater validations were necessary, which I had neglected, but 7 or more would be the size you would want, definitely not 6. If you feel otherwise, try it.

I don't need to try your code. Your code will produce undefined behavior, it is your use of numbers larger than the size of your array that is the problem. You must use the proper limit in your getline() call. If the size of the array is not large enough to hold the desired value then you must increase the size of the array, not just increase the number in the getline() function call. This is why it is usually recommended that you use a constant integral expression for both:

1
2
3
4
5
6
7
8
9
10
11
12
13
...

const size_t MAX_ARRAY = 10;

...

char str[MAX_ARRAY];

...

cin.getline(str, MAX_ARRAY); // Note '\n' is the default delimiter so you don't need it in the call.

...


And as I said you should really be using a std::string, it is much safer.

Last edited on
closed account (j3Rz8vqX)
You would be short 1 character; 0-8, rather than 0-9.
Example of your code:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
int main()
{
    const size_t MAX_ARRAY = 10;
    char str[MAX_ARRAY];
    cin.getline(str, MAX_ARRAY);
    cout<<str<<'\n';
    return 0;
}
0123456789
012345678

Process returned 0 (0x0)   execution time : 2.728 s
Press any key to continue.

You are right; force access of index [10] with '\n'.
Last edited on
You would be short 1 character; 0-8, rather than 0-9.

And your point is? I could enter any number of characters and the getline() would retrieve 9 characters from the stream, and then append the end of string character to the string as required. The code you have shown in your last post will not overrun the array because you are using the proper limit.

But the stream will be put into an error mode because it didn't find the delimiter. This signifies that there is still data in the buffer that needs to be retrieved.

Anyway, you can't do that.

You can't do what, exactly?
Topic archived. No new replies allowed.