我在将ptr->str
分配给令牌值时遇到问题。不确定ptr->str
上的内容是指向char的指针,因此是令牌。 printf
不打印char值。我收到运行时错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "C2A6E4_List-Driver.h"
typedef struct List
{
struct List *next; /* pointer to the next list node */
char *str; /* pointer to the string represented */
int count; /* # of occurrences of this string */
} List;
#endif
#define LINESIZE 256
#define DELIMETERS " "
typedef enum { false, true }bool;
List *newNode(void);
bool searchNode(List *head, char *key);
List *CreateList(FILE *fp)
{
List *head, *ptr;
int cnt = 0;
size_t length;
bool firstNode = true;
bool srchResult = false;
char buf[LINESIZE];
while (fgets(buf, (int)sizeof(buf), fp) != NULL) { /* read line of file*/
char *token = strtok(buf, DELIMETERS);
while (token != NULL) {
if (firstNode) {
ptr = newNode();
length = strlen(token) + 1;
// ptr->str = (char *)malloc(sizeof(char) * length);
ptr->next = head;
ptr->str = token;
ptr->count = 1;
head = ptr;
firstNode = false;
}
else {
srchResult = searchNode(head, token);
printf("srchResult= %d\n", srchResult);
if (srchResult) {
ptr = newNode();
length = strlen(token) + 1;
ptr->next = head;
ptr->str = token;
printf("ptr_str = %s", ptr->str);
ptr->count += 1;
head = ptr;
}//end if
}
printf("token = %s\n", token);
token = strtok(NULL, DELIMETERS);
}//end while
}// end while fgets
return head;
}
List *newNode(void)
{
List *ptr = (List *)malloc(sizeof(List));
if (ptr == NULL) {
fputs("Out of Memory\n ", stderr);
exit(EXIT_FAILURE);
}
return ptr;
}
bool searchNode(List *head, char *key)
{
List *cur = head;
bool cmpResult = false;
printf("key = %s\n", key);
while (cur) {
printf("call strmcmp\n");
printf("cur->str = \n", cur->str);
cmpResult = strcmp(cur->str, key);
printf("cmpResult = %d\n", cmpResult);
if (cmpResult == 0) {
return false;
cur->count += 1;
}
cur = cur->next;
printf("curnext\n");
}
if (cmpResult > 0 || cmpResult < 0)
cmpResult = true;
printf("return\n");
return cmpResult;
}
List *PrintList(const List *head)
{
List *cur = head;
while (cur) {
printf(" %s %d ea\n", cur->str, cur->count);
cur = cur->next;
}
return (List *)head;
}
void FreeList(List *head)
{
List *cur = head, *tmp;
while (cur) {
tmp = head;
head = head->next;
free(tmp);
}
}
答案 0 :(得分:0)
变量'head'未在createNode中初始化,因此以后在'ptr-&gt; next'中替换head可能会在以后遍历searchNode或PrintList中的树时导致意外行为。