0

Why is my C++ code triggering a stack overflow?

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{       
    cout<<"Enter an odd number for the order of magic square: ";
    cin>>num;

    int sqr[5][5];

    for (int i=0; i<num; i++)
        for (int j=0;j<num; j++)
            sqr [i][j]=0;

   return 0;

}

4
  • 2
    Where is num declared? Commented Oct 4, 2013 at 1:40
  • 1
    This happens if you key in values greater than 5 for num. Commented Oct 4, 2013 at 1:41
  • @Arun: I think it could also happen if you entered a non-integer. Commented Oct 4, 2013 at 1:42
  • @FredLarson, yeah right. Commented Oct 4, 2013 at 1:43

4 Answers 4

1
int sqr[5][5];

You defined sqr as double dimension array which col and row are both 5. The valid col/row are between [0..4], You need to make sure num < 5 && num > 0

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

Comments

0

You'd better usevector<vector<int> >, whose size be dynamically increased,

or change your code to

for (int i=0; i<num &&i < 5; i++)
    for (int j=0;j<num && j < 5; j++)
        sqr [i][j]=0;

since your declaration of sqr is sqr[5][5].

2 Comments

doesn't work. it doesn't even let me input any number
what num you want to input
0

may be there should exists: int num; or num may become a large number,resulting from a string. add: printf("%d",num); for test to see if it is larger than 4.

Comments

0

Did you want to create an n x n matrix based on input 'n'?

If so, you shouldn't statically allocate the matrix (see other answers for why). Assert if 'n' is not a number.

To create the matrix:

int **sqr = new int*[n];
for (int i = 0; i < n; i++)
    sqr[i] = new int[n];

This creates your created a 2D matrix of order n x n. To index into it, you can use sqr[row][col] (Remember: x denotes columns, y denotes rows! And don't forget to delete all this memory!)

If you want to use STL, then you can use create a vector of vectors without doing all this C style pointer stuff!

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.