如何在 C 中解决此分段错误错误?

时间:2021-04-03 02:40:31

标签: c gcc compiler-errors segmentation-fault

你能帮我解决这段代码吗?我是为了学术目的而写的,我也遇到了一些错误和分段错误。我会很感激的。

我正在学习 C 中的堆栈。我需要根据它们在 ASCII 表中的值和一些规则来组织字母(如字符容器中所示),如您在我的上一个函数中看到的那样。

为了解释我的代码,我从 2 个结构体开始。然后创建一个函数来分配内存,然后对堆栈中的元素进行分组。但是,最后一个函数可以使用为解决我的问题而创建的每个堆栈地址来组织我的数组。

typedef struct no {
    int dado;
    struct no *prx;
} no_t;

typedef struct pilha {
    int altura;
    no_t *topo;
} pilha_t;

pilha_t* pilha_cria () {
    pilha_t *p = (pilha_t*)malloc(sizeof(pilha_t));

    p->altura = 0;
    p->topo = NULL;
    return p;
}

void pilha_empilha (pilha_t *p, char conteiner) {
    if (p == NULL) return;

    no_t *no = (no_t*)malloc(sizeof(no_t));
    no->dado = conteiner;
    no->prx = p->topo;
    p->topo = no;

    p->altura++;
}

int pilha_organiza (int altura, char *conteiners, int quantidade) {
    
    pilha_t *p = pilha_cria();
    pilha_empilha(p, conteiners[0]);

    pilha_t *v = pilha_cria();
    pilha_empilha(v, p);    //register P address in V array
    v->altura++;

    int k = 1, j=0;
    while (k < quantidade) {
        
        if (p->topo->dado == conteiners[k] && p->altura < altura) {
            pilha_empilha(p, conteiners[k]);
        }
        else if (p->topo->dado < conteiners[k]) {
            p++;        //mudar de posicao
            p = pilha_cria();
            pilha_empilha(p, conteiners[k]);

            pilha_empilha(v, p); //register P address in V array
            v->altura++;
        }
        else {  
            
            while (j < quantidade) {
                if (v->topo->dado > conteiners[k]) {     //SEG FAULT HERE!
                    pilha_empilha(v, conteiners[k]);
                }
                j++;
                v++;
            }
        }
        k++;
    }
    printf("v altura: %d\n", v->altura);

    return 1;
}

int main() {
    int altura = 6;
    char conteiners[] = "AKKEFAGCFE";
    int quantidade = strlen(conteiners);

    if (quantidade == 0) return 0;

    pilha_organiza (altura, conteiners, quantidade);

    return 1;
}

答案:v->altura 应该是 4。 感谢阅读。

0 个答案:

没有答案
相关问题