下面的程序不适用于更大的字符串,但它适用于小字符串。我不知道为什么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)
答案 0 :(得分:1)
malloc(sizeof(pattern))
然后
strcpy(new_node->pattern , pattern);
不正确。
更好,使用strlen()
获取收到的字符串长度,然后分配内存,然后执行strcpy()
或memcpy()
复制已接收的字符串。
答案 1 :(得分:0)
尝试下面的代码,它会工作。你必须传递字符串长度而不是字符串本身
new_node->pattern = (char *)malloc(strlen(pattern)+1);
/* put in the data */
memcpy(new_node->pattern , pattern,strlen(pattern)+1);
答案 2 :(得分:0)
其他答案是正确的;但是,似乎有一个专用函数strdup
来做你想做的事情:
// Incorrect code
new_node->pattern = (char *)malloc(sizeof(pattern));
strcpy(new_node->pattern , pattern);
// Correct code, provided by user2083356
new_node->pattern = (char *)malloc(strlen(pattern)+1);
memcpy(new_node->pattern , pattern,strlen(pattern)+1);
// Does the same; seems easier to type and understand; also handles errors
new_node->pattern = strdup(pattern);