我知道我的标题不清楚,代码+示例会更清晰。 我想初始化一个char *(主要的“motSecret”,我的函数中的“mot”),其中包含一个随机选入文件的单词,将其作为一个函数。使用内存分配使该数组动态化。 函数中的变量初始化得很好,但是当我退出函数后打印值时,值会改变并变成“0 @”
以下是主要内容:
int main()
{
FILE* dico =NULL;
char *motSecret, *motRes;
char lettre=' ';
int check=0, nbCoups=10, longueur=0, nbMots=0;
Bool erreur = TRUE;
srand(time(NULL));
nbMots = scanDico(dico);
getWord(dico, nbMots, motSecret);
printf("Mot : %s", motSecret);
问题出现在函数getWord()之后。以下是此函数的代码:
void getWord(FILE* dico, int nbLignes, char *mot)
{
int numMotChoisi=rand() % nbLignes, nbChar=0;
char charActuel=' ';
dico = fopen("dico.txt", "r");
rewind(dico);
if(dico != NULL)
{
while (numMotChoisi > 0)
{
charActuel = fgetc(dico);
if (charActuel == '\n')
numMotChoisi--;
}
charActuel = ' ';
while(charActuel != '\n')
{
charActuel = fgetc(dico);
nbChar++;
}
fseek(dico,-(nbChar)-1,SEEK_CUR);
mot = malloc(nbChar * sizeof(char));
if(mot == NULL)
{
printf("Probleme d'allocation memoire");
exit(0);
}
fgets(mot, SIZE, dico);
mot[strlen(mot) - 1] = '\0';
printf("Mot = %s ", mot);
}
fclose(dico);
}
函数末尾的printf返回一个好的值,而mainf中的getWord()之后的printf显示函数中更改的值没有被“保存”...
其他方面,没有内存分配就可以正常工作。
我希望我足够清楚。如果我忘了告诉某事或者你需要更多信息,请告诉我。
答案 0 :(得分:3)
C在函数参数传递中使用pass by value
。
如果你想在另一个函数中分配内存,你需要一个双指针,如void getWord(FILE* dico, int nbLignes, char **mot)
。
作为一种级联效应,printf("Mot : %s", motSecret);
正在尝试访问未初始化的内存,从而导致未定义的行为。
建议:
我认为没有理由在FILE *dico
中使用getWord()
作为参数。很可能是当地人。
而不是使用双指针,我建议从getWord()
返回分配的指针,即将void getWord()
更改为char * getWord()
,添加return mot
和像motSecret = getWord(<params>)
答案 1 :(得分:1)
char *motSecret;
motSecret
是一个带main()
的局部变量,并未启动。
致电
getWord(dico, nbMots, motSecret);
您正在将一些未初始化的指针传递给函数getword()
。
在getword()
内,您正在为
char *mot;
并将一些数据写入此内存。
现在motSecret
不知道这个内存你必须将这个内存地址返回到main()
char *motSecret = getWord(dico, nbMots);
你的getword()应该是,
char *getWord(dico, nbMots);
并且在执行完所有操作后进入此内部,
return mot;