将内存分配给字符串数组

时间:2019-04-10 12:55:55

标签: c segmentation-fault

因此,我正在尝试分配内存以在其中插入文件名。我将结构Estado定义如下:

typedef struct estado{

    char modo;
    char jogador;
    char matriz[8][8];
    int pretas;
    int brancas;
    char *nome[10];
    int current;

} Estado;

我尝试这样做:

Estado insereFicheiro(Estado estado , char* nome){

    estado.nome[estado.current] = malloc(sizeof(char*));
    estado.nome[estado.current++] = nome;

    return estado;
}

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您显示的代码有两个问题:

  1. 使用

    estado.nome[estado.current] = malloc(sizeof(char*));
    

    您只为指针分配空间,而不为整个字符串分配空间。就像您创建一个包含一个指针的数组一样。您需要为字符串本身分配空间,该字符串的长度由strlen获得,最后还要为空终止符分配空间:

    estado.nome[estado.current] = malloc(strlen(nome) + 1);  // +1 for null-terminator
    
  2. 使用

    estado.nome[estado.current++] = nome;
    

    覆盖您在上面创建的指针。这相当于例如int a; a = 5; a = 10;,然后惊讶于a不再等于5。您需要复制字符串,而不是指针:

    strcpy(estado.nome[estado.current++], nome);
    

当然,完成后,您需要free在代码中稍后分配的内存。

当然,您应该进行一些边界检查,以确保您不会超出estado.nome数组的边界(即检查estado.current < 10)。

相关问题