gpt4 book ai didi

c - 对于较大尺寸的字符串,不会发生插入

转载 作者:行者123 更新时间:2023-11-30 15:28:44 25 4
gpt4 key购买 nike

下面的程序不适用于较大尺寸的字符串,但它适用于小字符串。我不确定为什么sortedInsert函数没有采用字符串的完整长度。该程序中也没有使用字符串长度限制。

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

/* Link list node */

struct node

{

char* pattern;

struct node* next;

};

/* function to insert a new_node in a list. Note that this

* function expects a pointer to head_ref as this can modify the

* head of the input linked list (similar to push())*/

void sortedInsert(struct node** head_ref, struct node* new_node)

{

struct node* current;

/* Special case for the head end */

if (*head_ref == NULL || (strcmp((*head_ref)->pattern ,new_node->pattern)> 0))

{

new_node->next = *head_ref;

*head_ref = new_node;

}

else

{

/* Locate the node before the point of insertion */

current = *head_ref;

while (current->next!=NULL &&

strcmp(current->next->pattern, new_node->pattern)< 0)

{

current = current->next;

}

new_node->next = current->next;

current->next = new_node;

}

}

/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */

/* A utility function to create a new node */

struct node *newNode( char * pattern)

{

/* allocate node */

struct node* new_node =

(struct node*) malloc(sizeof(struct node));

new_node->pattern = (char *)malloc(sizeof(pattern));

/* put in the data */

strcpy(new_node->pattern , pattern);



new_node->next = NULL;

return new_node;

}

/* Function to print linked list */

void printList(struct node *head)

{





struct node *temp = head;

while(temp != NULL)

{

printf("\n%s", temp->pattern);

temp = temp->next;

}

}

/* Drier program to test count function*/

int main()

{

/* Start with the empty list */

struct node* head = NULL;

struct node* new_node = newNode("a.b.c.d.e.f.g.h.h.j.k.l.m.n.o");

sortedInsert(&head, new_node);

new_node = newNode("a.b.c.de.f.g.h.j.k.l.m.t.y.u.k");

sortedInsert(&head, new_node);

new_node = newNode("a.b.c.d.ef.g.h.h.k.j.l.y.u.l.p");

sortedInsert(&head, new_node);

printf("\n Created Linked List\n");

printList(head);



return 0;

}

这是上述程序的输出,其中可以看到意外的输出。输出:

已创建链接列表

a.b.c.d.e.f.)

a.b.c.d.ef.g.h.h.k.j.l.y.u.l.p

a.b.c.de.f.g)

最佳答案

malloc(sizeof(pattern))

然后

strcpy(new_node->pattern,pattern); 不正确。

更好,使用strlen()获取接收到的字符串长度,然后分配内存,然后执行strcpy()memcpy()复制接收到的字符串。

关于c - 对于较大尺寸的字符串,不会发生插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26468788/

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