user2844883
user2844883

Reputation: 1

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

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;

}

Upvotes: 0

Views: 105

Answers (4)

Raja
Raja

Reputation: 3106

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!

Upvotes: 0

xzfn
xzfn

Reputation: 1

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.

Upvotes: 0

billz
billz

Reputation: 45470

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

Upvotes: 1

CS Pei
CS Pei

Reputation: 11047

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].

Upvotes: 0

Related Questions