首页 > 解决方案 > 将值设置为结构指针

问题描述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
    char** thingSize;
} Thing;

typedef struct {
    Thing* thing;
} Game;

void load_array(Thing* thing) {
    int i, j;
    char **emptyThing = malloc(sizeof(char**));
    emptyThing = malloc(sizeof(char*)*9);
    for(i=0; i<9; i++) {
        emptyThing[i] = malloc(sizeof(char)*9);
    }
    thing -> thingSize = emptyThing;
    free(emptyThing);
}

int main(int argc, char* argv[]) {
    Game* game;
    load_array(game -> thing);
    printf("HI");
}

我遇到了分段错误,我发现问题线是。 thing -> thingSize = emptyThing; 我正在尝试将thingSize 设置为等于emptyThing 的二维数组。

标签: c

解决方案


正如 Fredrik 所说,游戏指针没有被初始化为任何东西。它持有一个垃圾值,当取消引用它时,你会得到一个段错误。


推荐阅读