c中的动态位置不起作用

时间:2016-04-14 03:34:45

标签: c pointers structure allocation

每次尝试运行案例时,我都会退出(1)(如果分配中有错误)1。我没有想法为什么,我可以得到一些帮助吗?

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

typedef struct hospede{             //guest
    int numreg;     //register num
    char nome[80];
    int acompanhante;   //n of ppl
    int dias;   //time to stay
    estado tabela;
}hospede;

typedef struct quarto{          //room
    int num;    //num do quarto
    char categoria;     //[S] ou [F]
    char status;        //[L] ou [O]
    estado stats;
    }quarto;

void alocaHospede(hospede **hosp, int tam);
void alocaQuartos(quarto **quar, int tam);
void geraQuartos(quarto *quar);
void checkIn(hospede *hosp, int tam);

int main()
{
    hospede *hpd = NULL;
    quarto *qrt = NULL;
    quarto quart;
    int qtd = 0;
    char op;
    int x;

    qrt = &quart;
    geraQuartos(qrt);
    do{
        printf("\n1-CheckIn\n>");
        scanf("%i", &x);
        fflush(stdin);
        switch(x){
        case 1:
            alocaHospede(&hpd, qtd+1);       
            checkIn(hpd, qtd);
        }
        printf("\nDeseja continuar? \n");
        scanf("%c", &op);
        fflush(stdin);
    }while(op!='n' && op!='N');

    return 0;
}
void checkIn(hospede *hosp, int tam){
    printf("\nwork\n");
}//checkIn
void alocaHospede(hospede **hosp, int tam){
    *hosp = (hospede*)realloc(*hosp, tam*sizeof(hospede));
    if(*hosp == NULL)
        exit(1);
}//aloca hospede

void alocaQuartos(quarto **quar, int tam){
if((*quar = (quarto *) realloc(*quar, tam * sizeof(quarto)))== NULL)
    exit(1);
}//alocaQuartos


void geraQuartos(quarto *quar){
    int i;
    for(i=0;i<15;i++,quar++){
        (*quar).num = i+1;
    }
}//geraQuartos

OBS:

我删除了一些尚未用于缩短代码的结构和联合,我也会对房间进行分配,我认为这也是同样的问题。

2 个答案:

答案 0 :(得分:1)

geraQuartos(qrt)导致堆栈溢出,因为夸脱只有1个入口加长但你在函数内写入第1~15个条目。 堆栈溢出会发生任何奇怪的事情。

答案 1 :(得分:1)

geraQuartos中的quartos循环将其参数视为指向15个hpd结构数组的指针。但它只是指向一个结构的指针,因此它在对象的边界之外写作。这会导致未定义的行为,在这种情况下,它会覆盖NULL,因此它不是realloc。这会导致NULL失败,因为第一个参数不是malloc或先前由quart返回的指针。

quarto quart[15]; 的声明更改为:

geraQuartos(quart);

然后执行:

crt.Screen.Send "cat myfile.txt | grep 'L[0-9]*' " &  vbcr
相关问题