Segmentation Fault

I am making a program that creates a 2d array and inputs a file/displays the file.
it compiles, however when I execute it with the input file:
./a.out < program1input.dat
the program says segmentation fault(core dumped)
how do i fix this?

here is my code if that helps:

#include <iostream>
#define HEIGHT 10
#define WIDTH 10

using namespace std;

int main() {

int output [HEIGHT][WIDTH];
int a, b;

cin >> output[a][b];

for(a = 0; a <= HEIGHT; a++)

for(b = 0; b <= WIDTH; b++)
{
output[a][b];
}
cout << output << endl;

return 0;
}
Anything at output[HEIGHT][x] or at output[x][WIDTH] is outside the bounds of output, and accessing it is a buffer overflow.
a and b must be < than HEIGHT and WIDTH respectively.
i am still recieving the seg fault. i changed that portion of the code. could it be because the input file could have more than just a single digit number for each slot in the array?
Ah, yes. Reading more carefully, I see the following problems:
* a and b are uninitialized when you read from std::cin the first time.
* Your loop doesn't actually do anything. You probably meant to put the cin >> etc inside the loop.
* cout << output will not do what you expect.
alrighty so ill move my cin>> inside.
also on the cout<< am i missing the parameters "[][]"?
Cannot be <= only <
remember, theres only 1 reason why "segmentation fault" error appears, that is accessing an invalid memory adress. in your case , that is out of bounds.

out of bounds is the same with accessing invalid memory adress.

let's see

a <= HEIGHT;

this means if a is 10 the loop will still continue (same goes for b)

if both a and b hit 10
the statement inside your loops will be like this output[10][10]
which is already out of bounds of your array, why?
the index count of an array always starts with 0, so the last index count of your array is 9 instead of 10.

0123456789 = 10 numbers // this is your array
012345678910 = 11 numbers

EDIT: for code tags.
Last edited on
Topic archived. No new replies allowed.