Getting a segfault. Why?

时间:2016-04-25 09:24:20

标签: c++ segmentation-fault

I keep getting a segfault on grid[x][y] = rand(); Any help? I've tried replacing the random function call with a number to see if thats what was causing the problem but it doesnt seem so.. I've got no idea

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){

int x;
int y;
int gridMult;
int grid[gridMult][gridMult];

srand(time(NULL));

std::cout << "Enter grid size:: ";
std::cin >> gridMult;

while(x < gridMult){
    while(y < gridMult){
        grid[x][y] = rand();
        y++;
    }
x++;
}

for(int x = 0; x < gridMult; x++){
    for(int y = 0; y < gridMult; y++){
        std::cout << grid[x][y];
    }
    std::cout << std::endl;
}
return 0;
}

1 个答案:

答案 0 :(得分:3)

In those two lines

int gridMult;
int grid[gridMult][gridMult];

gridMult is undefined, so how do you expect the compiler to properly size up your array?


Then when you get to the loops:

while(x < gridMult){
    while(y < gridMult){
        grid[x][y] = rand();

x and y are also undefined.

In general, I'd change those loops to for (or range-for) to scope the iteration variables as narrowly as possible.


If you want it to allocate dynamically based on user input, use std::vector and resize it to the desired size.

I'd also add that 2-dimensional arrays are typically realized on a 1-dimensional storage vector and 2-dimensional view on top of it, instead of nested vectors, so you might want to read about those patterns.