gpt4 book ai didi

c - 全局数组在 while 循环内不更新?

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

我有一个结构数组,在 while 循环中我向那个数组添加了东西,但是当我打印出这个数组时我得到了错误的输出? (最后添加的元素被打印n次,n是我添加的东西的个数)

我用谷歌搜索了一下,我认为这是因为 Bash 中的 while 循环创建了一个子 shell,不太确定。

任何帮助将不胜感激(请耐心等待我只是学生!!)

使用 Mac OSX 山狮Xcode 4 海湾合作委员会

代码:

#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

typedef struct{
char* one;
char* two;
} Node;

Node nodes[100];
int count = 0;

void add(char *one,char*two){
Node newNode = {one,two};
nodes[count]= newNode;

printf("one: %s\n",one);
printf("two: %s\n",two);

count++;
}

void print(){
int x;
for (x = 0; x < 10; x++)
printf("%d : (%s, %s) \n",x,nodes[x].one, nodes[x].two);
}

void check(char **arg)
{
if(strcmp(*arg, "Add") == 0)
add(arg[1],arg[2]);
else if(strcmp(*arg,"print") == 0)
print();
else
printf("Error syntax Enter either: \n Add [item1][item2]\n OR \n print\n");
}

void readandParseInput(char *line,char **arg)
{
if (fgets (line, 512, stdin)!= NULL) {
char * pch;
pch = strtok (line," \n\t");
int count = 0;
arg[0] = pch;

while (pch != NULL)
{
count++;
pch = strtok (NULL, " \n\t");
arg[count] = pch;
}
}else{
printf("\n");
exit(0);
}
}

int main()
{
int i;
for(i = 0;i <100; i++){
nodes[i].one = ".";
nodes[i].two = ".";
}

char line[512]; /* the input line */
char *arg[50]; /* the command line argument */

while (1)
{
readandParseInput(line,arg);
if(arg[0] != NULL)
check(arg);
}
return(0);
}

最佳答案

strtok()返回指向最初传递的缓冲区中不同元素的指针。这意味着数组中的所有条目都将指向同一缓冲区的不同元素,名为 line。您需要复制 strtok() 返回的指针:

无论哪种情况,内存都必须在不再需要时free()d。

关于c - 全局数组在 while 循环内不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949479/

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