在C中初始化ADT

时间:2018-08-22 17:28:35

标签: c malloc

.h中有以下ADT定义

struct BotStruct_t {
    int n_bots;
    char** nombre;
    char** caracter;
    int* fichas;
    int* carta_maxima;
};

typedef struct BotStruct_t * BotPtr_t;

int initBot(BotPtr_t bot);

在.c

int initBot(BotPtr_t bot) {
    bot = malloc(sizeof(struct BotStruct_t));
    if (bot == NULL) return 1;

    FILE* fp = fopen("/home/norhther/CLionProjects/blackjack/bot.txt","r");

    if (fp == NULL) {
        printf("El archivo de los bots no existe\n");
        fclose(fp);
        return 1;
    }
    else {
        char* line = NULL;
        size_t len = 0;
        getline(&line, &len, fp);
        int n_bots = atoi(line);
        bot->n_bots = n_bots;
        char** nombres_bots = malloc( sizeof(char*) * n_bots);
        char** caracter = malloc( sizeof(char*) * n_bots);
        int* fichas = malloc (sizeof (int) * n_bots);
        int* carta_maxima = malloc (sizeof (int) * n_bots);

        if (nombres_bots == NULL || caracter == NULL || fichas == NULL || carta_maxima == NULL) return 1;
        int i;
        for (i = 0; i < n_bots; i++) {
            getline(&line, &len, fp);
            nombres_bots[i] = strdup(line);
            getline(&line, &len, fp);
            fichas[i] = atoi(line);
            getline(&line, &len, fp);
            caracter[i] = strdup(line);
            getline(&line, &len, fp);
            carta_maxima[i] = atoi(line);
        }
        bot->nombre = nombres_bots;
        bot->caracter = caracter;
        bot->fichas = fichas;
        bot->carta_maxima = carta_maxima;
    }

    fclose(fp);
    return 0;
}

最后我的主要人

int main() {
    BotPtr_t bot;
    initBot(bot);
}

这里的问题是,当我尝试访问bot的任何元素时,例如bot-> carta_maxima [0],我得到了SIGSEGV。如果我尝试在.c中的init函数中执行相同的操作,那么它将起作用。我真的不明白,因为我正在使用指针,并且还在做适当的malloc。 这里有任何线索吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

您似乎正在尝试通过init参数返回指向您的BotStruct_t的指针。问题在于,在C中,所有参数都由-value-传递,因此bot例程中的指针initBot()对于该例程而言是本地的。

您需要做的是将POINTER传递给指向您的BotStruct_t的指针,这样您就可以通过指针到指针将指针分配给调用者的指针版本。即将BotPtr_t bot更改为BotPtr_t * pbot,分配*pbot = malloc(...),依此类推。