gpt4 book ai didi

常用词检查循环不起作用

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

我想制作一个程序来读取两个文件并给出常用词作为 2-gram。我写了下面的代码。

here is the node

   struct node {
char *string;
struct node *next;
};

here is the check loop

struct node *sw1, *sw2, *sw1_head;

//first 1 and first2 is the head of linked lists that holds text's each word seperatly. i created before.

first1 = first1_head; // _ head is the same as first1 and first2
first2 = first2_head;

//sw1 and sw2 are the pointers that holds always second words.
sw2 = first2->next;
sw1 = first1->next;
sw1_head = sw1;

//these chars are used to concat two words
char destination1[50];
char destination2[50];

while(sw2 != NULL){

strcpy(destination2,first2->string);
strcat(destination2,sw2->string);

while(sw1 != NULL){

strcpy(destination1,first1->string);
strcat(destination1,sw1->string);
// printf("%s\n", destination1);
if(strcmp(destination2, destination1) == 0) {

insert(&matched2, destination1);//matched holds common words

}

sw1 = sw1->next;
first1 = first1->next;

}

sw1 = sw1_head;//sets both sw1 and first1 to their past positions.
first1 = first1_head;
sw2 = sw2->next;
first2 = first2->next;
}

当我尝试打印ma​​tched2链接列表时。它给了我 21 adocument 这是第一个文件的最后两个单词,这甚至不常见。我认为 strcmp 函数有问题。

我之前问过类似的问题,但它们不一样。

这是我打印matched2链接列表的方法。

while(matched2 != NULL){
printf("%s\n", matched2->string);
matched2 = matched2->next;
}

这是插入方法

void insert(struct node **new_node, char* new_data){

/* allocate node */
struct node *ptr1 =(struct node*) malloc(sizeof(struct node));
/* put in the data */
ptr1->string = new_data;
ptr1->next = NULL;
if(new_node == NULL){
*new_node = ptr1; return;
}
ptr1->next = *new_node;
*new_node = ptr1;

最佳答案

将您的 insert 函数更改为:

void insert(struct node **new_node, char* new_data){

/* allocate node */
struct node *ptr1 =(struct node*) malloc(sizeof(struct node));
/* put in the data */
ptr1->string = strdup(new_data);
ptr1->next = NULL;
if(new_node == NULL){
*new_node = ptr1; return;
}
ptr1->next = *new_node;
*new_node = ptr1;

唯一的变化是行 ptr1->string = new_data 应该 strdup new_data

如果仔细观察,会发现 insert 是通过 destination1 调用的,它是一个固定缓冲区。因此,如果每次创建新节点时不复制其内容,则每个节点最终都将指向相同的缓冲区,其中将包含最后两个单词。

还有

那部分

if(new_node == NULL){
*new_node = ptr1; return;
}

可能是死代码,也就是说,new_node永远不会为NULL,也许是因为您的列表头已预先初始化(如果您不发布完整的代码,我们将永远无法确定)。

如果这不是死代码(您可以通过在if内部进行printf'ing来检查它),那么这里潜伏着一个错误,因为当new_nodeNULL,然后*new_node取消引用NULL,这应该触发SIGSEGV。

关于常用词检查循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46795225/

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