views:

159

answers:

4

So I'm starting my magic square hw, where I ask the user to enter a odd integer, and it will create a magic square off that. I have to use pointers and arrays as that is all I have learned so far. Not asking how to do the magic square, but what is causing a segmentation fault, im probably not doing pointers to 2d arrays correctly

#include <iostream>
using namespace std;

int main()
{
int **ptr;
int odd;
do 
{
 cout << "Enter a odd number to create a magic square: ";
 cin >> odd;
}while(odd % 2 != 1);

ptr = new int *[odd]; //creates a new array of pointers to int objects
for(int i = 0; i < odd; i++)
 ptr[i] = new int[odd];

//set it all to 0
for(int i = 0; i < odd; i++)
{
 for (int j = 0; j < odd; j++)
 { 
  ptr[i][j] = 0;
  cout << ptr[i][j];
 }
}
int row = odd;
int column = odd / 2;
int lastrow = row;
int lastcolumn = column;

//begin adding numbers to magic square
ptr[row][column] = 1;
for (int i = 2; i < odd * odd; i++)
{

}

//delete
for(int i = 0 ; i < odd; i++)
 delete [] ptr[i];
delete [] ptr;
return 0;
}
+1  A: 

The first thing to do when you get a segmentation fault is either to grab a debugger and track down exactly where the segfault happens, or (simpler), to add a lot of printouts to cerr in the code, so you can see how much of your code gets executed before the segfault.

Additional hint: Use cerr rather than cout, to avoid buffering which might otherwise keep you from seeing some output which you should get before the error, and always add a newline to each printout to avoid having it clobbered by the next prompt in the shell where you run your program.

Rasmus Kaj
+3  A: 

int row=odd; should be int row=odd-1;
You are later indexing with row, so you get to array[size_of_array], which is always out of bounds.

Arkaitz Jimenez
This is probably correct, but since the question relates to a homework, I think it is actually more helpfull to tell Raptrex how to find the error than to tell him where the error is ...
Rasmus Kaj
thanks that makes a lot of sense
Raptrex
A: 

This:

ptr[row][column] = 1;

accesses array out of bounds (hint: ptr[row] will likely be NULL in most malloc implementations).

Employed Russian
A: 

gdb is able to tell you exactly when the segfault happens and lets you print the data from it. Its probably your best option for figuring out where the segfault happens.

Compile your program with -g (Assuming your using GCC)

mathepic