gpt4 book ai didi

c - 传递的双指针在循环期间被破坏?

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:41 25 4
gpt4 key购买 nike

char **rhyme;  // init my double pointer
rhyme=inputrhyme(); // calls below function to input the rhyme

char** inputrhyme(){
char **rhyme, *temp, *token, BUFF[300], s[2]=" ";
int length=0;
rhyme=malloc(length * sizeof(char*));
printf("please enter a rhyme: \n");
scanf(" %[^\n]",BUFF);
token = strtok(BUFF, s);
while( token != NULL )
{
length++;
temp=realloc(rhyme, length* sizeof(char*));
if (temp==NULL){
printf("fatal error!\n");
exit(EXIT_FAILURE);
}
rhyme=temp;
rhyme[length-1]=token;
token = strtok(NULL, s);
}
length++;
temp=realloc(rhyme, length* sizeof(char*));
if (temp==NULL){
printf("fatal error!\n");
exit(EXIT_FAILURE);
}
rhyme=temp;
rhyme[length-1]=NULL;

return rhyme;
}

firstNode=sayRhyme(rhyme, firstNode); // goes through the rhyme saying each word

NodePtr sayRhyme(char **rhyme, NodePtr starting_player){
int index;
NodePtr temp=starting_player;
printf(" %s\n", rhyme[6]); // works fine for all valid values
for (index=0; index<9; index++){
printf("---------%d %s\n",index, rhyme[index]); // problem area
}

以上就是几乎所有涉及到这个韵的代码了。当我将双指针传递给我的函数时,我只需要读取它,所以我没有传递指向它的指针。我可以读取押韵中的任何值,但是当我尝试将它放入一个循环时,数据会以某种方式损坏。这是我得到的输出:

please enter a rhyme:
help im stuck in a computer for real now *user input*
help
im
stuck
in
a
computer
for
real
now
first word was help
for
---------0 help
---------1 im
---------2 stuc$
---------3
---------4

---------5
---------6 for
---------7 ▄²(
---------8 ≥7vÅ≥7vδ╛ΣW
player 0 is eliminated

我不确定我在这里做错了什么。我尝试将双指针作为三重指针传递并以相同的结果引用它。

最佳答案

您正在将字符串保存到本地数组 BUFF 中,该数组将存储在堆栈中。

当您调用 strtok 将其分解为标记时,它将返回指向 BUFF 数组的指针。

当你从你的函数返回时,堆栈空间被释放并且可以被程序的其他部分重用。

您需要将字符串存储在更好的地方,例如在全局数组或分配的内存块中。

关于c - 传递的双指针在循环期间被破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21736835/

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