Why does my code not work

Problem statement:
You are given a group of N letters, and a 2D array of X, Y dimensions. You have to complete the 2D array with the pattern that derives from the character group. (I don't know if I explained the problem adequately but you'll understand from the input/output example.)

Input:
3 3 4
Ε Α Β

Output:
ΕΑΒΕ
ΑΒΕΑ
ΒΕΑΒ

I wrote the following code, but I don't understand where I made a mistake.
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
 #include<iostream>
using namespace std;

int main(){
int n;
int x, y;
cin>>n;
cin>>x>>y;

char chars[n];
char pattern [x][y];

for (int i=0; i<n; i++){
    cin>>chars[i];
}
int counter = 0;
for (int j=0; j<x; j++){
    for (int a=0; a<y; a++){
        pattern [j][a] = chars[counter];
        if (counter==n){
            counter=0;
        }
        else{
            counter++;
        }
    }
}
for (int q=0; q<x; q++){
    for (int w=0; w<y; w++){
        cout<<pattern[q][w]<<" ";
    }
    cout<<endl;
}
}
Last edited on
1
2
char chars[n];
char pattern [x][y];


You can't do this in c++. When you create an array you have to give it a fixed value. Such as char chars[10]; If you want to do what you're doing. You will have to allocate memory on the heap.

http://www.cplusplus.com/doc/tutorial/dynamic/
https://www.youtube.com/watch?v=_749lj2yb8Y

1
2
        pattern [j][a] = chars[counter];
        if (counter==n){ //if this is true, then you just accessed your array out of bounds 
Topic archived. No new replies allowed.