C分段故障编程

时间:2014-04-19 14:17:18

标签: c

我遇到分段错误的问题。我不确定阵列。 我需要得到这样的输出

这是我的代码的一部分。 (结构和枚举必须保持不变)

编辑:第二个malloc修复,这只是我的代码的一部分,我得到分段错误,编译时警告:未使用的变量'title'和运行时的分段错误

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef enum {
    GAME1,
    GAME2,
    GAME3,
} TITLE;


typedef struct abx {
    TITLE **title;  
} ABX;



string[]="ABCACC|ACCBAA|BBCABC"

ABX *abx = (ABX*)malloc(sizeof(ABX));

TITLE **title = (TITLE**)malloc(sizeof(TITLE*));

    width = height = 0;
    while (string[i] !='\0') {
        abx->title[height][width]=(TITLE)malloc(sizeof(TITLE*));

        if(string[i]=='A'){
            abx->title[height][width] = GAME1;
            break;
        }
        if(string[i]=='B'){
            abx->title[height][width] = GAME2;
            break;
        }
        if(string[i]=='C'){
            abx->title[height][width] = GAME3;
            break;
        }
        if (string[i]=='|'){
            height++;
            width = 0;
        } 
        else{
            width++;
        }
        i++;
    }

1 个答案:

答案 0 :(得分:0)

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef enum {
    GAME1,
    GAME2,
    GAME3,
} TITLE;

typedef struct abx {
    TITLE **title;  
} ABX;

int main(){
    char string[]="ABCACC|ACCBAA|BBCABC";
    ABX *abx = malloc(sizeof(ABX));
    int i, len, w, h, width, height;
    char ch;
    len = width = height = 0;
    for(i=0;(ch=string[i]) != '\0';++i){
        if(ch == '|'){
            ++height;
            if(width<len)
                width = len;
            len = 0;
        } else
            ++len;
    }
    ++height;
    if(width<len)
        width = len;

    abx->title =malloc(height*sizeof(TITLE*));
    for(h=0;h<height;++h)
        abx->title[h]=malloc(width*sizeof(TITLE));

    for(h=w=i=0;string[i]!='\0';++i){
        if(string[i]=='A'){
            abx->title[h][w++] = GAME1;
            continue;
        }
        if(string[i]=='B'){
            abx->title[h][w++] = GAME2;
            continue;
        }
        if(string[i]=='C'){
            abx->title[h][w++] = GAME3;
            continue;
        }
        if (string[i]=='|'){
            ++h;
            w = 0;
        } 
    }
    ...
}