gpt4 book ai didi

c - 结构数组测试时循环未触发

转载 作者:行者123 更新时间:2023-11-30 14:50:39 25 4
gpt4 key购买 nike

我刚刚开始探索 C,所以我会很感激任何代码风格的建议。然而,我的具体问题是理解为什么我的 else if 条件没有被触发。正如您在评论中看到的,我意识到我的 loop->word 似乎从未初始化过,但第二次通过 for 循环 我认为至少应该加一个字吗?

代码:

 typedef struct node{
char word[15];
int count;
} node;


int main(int argc, char *argv[]){
int word_size = 500, dict_size=10;
char words[word_size];

// main prompt
printf("Enter some words: ");
fgets(words, word_size, stdin);

// create a list of nodes, and iterator through array
struct node dict[dict_size];
struct node *head = dict;
struct node *loop = dict;

// pointer for tokenization, starts at [0] until delimiter
char *pch;
pch = strtok(words, " ");
// TODO: dict[0] so that last is equal to 1, and can use that as max loop?

// keep track of how many nodes have been updated
int i, j, last = 0;

while(pch != NULL){
printf("pch == %s\n", pch); // this works

for(i=0; i<dict_size; i++, loop++) {
printf("inner = %d\n", i); // this works
printf("loop->word == %s\n", loop->word); // realize i'm testing against nonsense?

if(loop->word == pch){
// loop through each dict element, looking for matching word
// increment the value pointed to by loop->count
printf("%s was found in dict[%d], incrementing counter", loop->word, loop->count);
loop->count = loop->count + 1;
break;

} else if(i == dict_size){
// key doesn't exist so update the next struct
printf("adding %s, with count 1.\n", pch);
strcpy(dict[last].word, pch);
dict[last].count = 1;
last++;
}
}
// lastly move token, and reset pointer @ head of the dictionary
pch = strtok(NULL, " ");
loop = head;
}

// set pointers to null?
loop = NULL;
head = NULL;
printf("done");

编辑:对代码墙感到抱歉,不确定解决 C 问题所需的最少代码是什么。

最佳答案

  • 在条件为 i<dict_size 的 for 循环内您如何期望它等于 dict_size if 是 for 循环体中唯一不递增的地方。

  • 您可能想要的是,循环结束后 - 检查是否 i == dict_size那么你就可以确定它没有被发现。在 for 循环中,您正在检查 i == dict_size这将在它之外。

  • 还有loop->word == pch正在比较两个指针 - 但您想比较两个字符串 - 这将使用 strcmp 来完成。所以代码的结构将是

    for(i = ..; i < dict_size ; ... ){
    if(strcmp(loop->word, pch) == 0){
    /* found */
    }
    ...
    }
    if( i == dict_size){
    /* not found */
    }
  • fgets应检查返回值以检查函数调用的失败或成功。这个级别的错误检查很重要。

关于c - 结构数组测试时循环未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48913115/

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