1

I need help debugging the following block of code. This block of code gives me a segmentation fault error only when i attempt to assign an appropriate(char) value to squares[ i ][ j ]. How can I fix this?

for(int i=0;i<sides;i++){
    for(int j=0;i<sides;j++){
        squares[i][j] = '';
    }
}  

I declared the array squares[][] with the following code before the nested for loop:

char **squares = new(nothrow) char*[sides-1];
for(int i=0; i < sides-1; i++){
    squares[i] = new char[sides-1];
}
2
  • 4
    the inner loop has a i<sides instead of j<sides Commented Apr 24, 2015 at 12:26
  • 4
    you only created sides-1 arrays, but you try to access "sides" number of them in your loop(change the i<sides to i<sides-1) Commented Apr 24, 2015 at 12:26

2 Answers 2

2

A much better way to declare an empty string array would be to use String[] Don't forget you're in C++. And in your case, since it looks like you're wanting to do a square array, you could use a std::array if the sizes are known or a std::vector for unknown sizes. Now for the strict answer, use j in your second loop instead of i.

for(int i=0;i<sides - 1;i++){
    for(int j=0;j<sides - 1;j++){
        squares[i][j] = '';
    }
}  

I'm strongly encouraging you to try to look at your problem with Strings instead of re-inventing the wheel. (Thanks to NathanOliver & jsantander for the help)

Sign up to request clarification or add additional context in comments.

4 Comments

Don't forget what @Creis said: the loop limits are wrong too.
@jsantander yeah, thanks for the reminder, i'm changing that right now
It would even be better to use a std::array if the sizes are known or a std::vector for unknown sizes.
@NathanOliver Updating my answer with that, thanks for your output nathan
0

In your declaration,try to change the i < sides - 1 to i < sides

char **squares = new(nothrow) char*[sides-1];
for(int i=0; i < sides; i++){
    squares[i] = new char[sides-1];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.