gpt4 book ai didi

c - 为字符串数组分配内存

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:34 24 4
gpt4 key购买 nike

因此,我正在尝试分配内存以在其中插入文件名。我的结构 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. 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 )。

关于c - 为字符串数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com