C 将内存分配到字符串数组
所以,我尝试分配内存来在其中插入文件名。我的struct Estado定义如下: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
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=10然后惊奇地发现a
不再等于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。我还建议将增量移出索引运算符,与将其放在副本之后相比,它没有太多优势。