开发者

C++ char/string reading problem

Again, I'm trying to make a simple program. It will read some kind of board, at the size of RxC. Each items on the board are letters, separated with spaces. This is a sample board:

A B C

D E F

G H I

After that, it will read an integer N, and for next N lines, read a string and process them one by one based on the given board. But now, I'm facing a problem with how to read them. Here is the code :

#include<iostream>
using namespace std;

int r,c,el; char **arr;

int main()
{
    char *tes;
    int n;

    //start reading the puzzle
    cin >> r >> c; el=r;
    cout << el << endl;
    arr = new char * [3*(r+c)-6];
    for(int i=0;i<r;i++)
    {
        arr[i] = new char[c+1];
        for(int j=0;j<c;j++) cin >> arr[i][j];
        arr[i][c] = '\0';
    }
    for(int i=0;i<el;i++) cout << arr[i] << endl;

    cin >> n;
    while(n>0)
    {
        n--;
        cin >> tes;
        cout << tes << endl;
    }
}

I don't know what's wrong with this, it's seems OK to me. However, it always get runtime errors. I'm using latest MinGW and gdb debugger. On gdb I saw something like

"received signal SIGSEGV. Segmentation fault"

, and an 0xC0000005 error. I really have no idea what's going on here. I've tried both iostream(cin&cout) and cstdio(scanf,puts,etc.)

P.S.: I declare the variables globally, because I will process them on a different function out of开发者_如何学C the main() function. I set the size of the "height" of the array to (3*(r+c)-6), not to the normal (r) is because I will use the same array to store another strings later.


In addition to the problems already noted by others, you haven't allocated any memory for tes - it's just a dangling pointer.

Change:

char *tes;

to, e.g.:

char tes[80];


A board of size R*C needs, not very surprisingly, r*c chars of storage. I fail to understand why you're allocating the board in so many steps. A single char* board = new char[r * c]; should do it, then just keep track of where in the array your're reading.


Segmentation fault usually means you are trying to access memory which hasn't been allocated, for instance

char* mystr = (char*)malloc(3*sizeof(char));
mystr[4] = 0.0;

will (most likely) cause a seg fault because you're accessing memory which you didn't allocate (mystr goes from 0 - 2).

Are you sure you're allocating the memory correctly? I'm not sure why you have 3*(r+c)-6.


Further to unwind's answer, your array has size 3*(r+c)-6, but you are looping over values i = 0; i < r;, which depending on the values may just run out of bounds (plus it makes no sense).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜