Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将内存分配到字符串数组_C_Segmentation Fault - Fatal编程技术网

C 将内存分配到字符串数组

C 将内存分配到字符串数组,c,segmentation-fault,C,Segmentation Fault,所以,我尝试分配内存来在其中插入文件名。我的struct 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 , c

所以,我尝试分配内存来在其中插入文件名。我的struct 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;
}

我做错了什么?

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

  • estado.nome[estado.current] = malloc(sizeof(char*));
    
    estado.nome[estado.current++] = nome;
    
    只为指针分配空间,而不是整个字符串。这就像创建一个指针数组一样。您需要为字符串本身分配空间,该字符串的长度可以从
    strlen
    中获得,并且还需要为末尾的空终止符分配空间:

    estado.nome[estado.current] = malloc(strlen(nome) + 1);  // +1 for null-terminator
    
  • estado.nome[estado.current] = malloc(sizeof(char*));
    
    estado.nome[estado.current++] = nome;
    
    覆盖上面创建的指针。这相当于,例如,
    inta;a=5;a=10a
    不再等于
    5
    。您需要复制字符串,而不是指针:

    strcpy(estado.nome[estado.current++], nome);
    
  • 当然,您需要
    释放
    代码中稍后分配的内存,一旦完成


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

    您需要指定字符串的长度,并更改为
    estado.nome[estado.current]=malloc(20*sizeof(char)
    例如,对于赋值使用
    strcpy
    @aragon,`sizeof(char)根据定义在C中总是1。我还建议将增量移出索引运算符,与将其放在副本之后相比,它没有太多优势。