c - 如何将结构存储为链表节点,并且该结构具有 char *words[10] 这是一个已解析的字符串?

标签 c string linked-list

更具体地说,我的问题是,我想在链表中存储一个结构体words,每个节点都有char *words[10],这个char *words[10] 来自解析后的字符串,每个words[i] 是该字符串中的一个单词(前10 个单词)。

我有一个字符串(在我的问题中,该字符串是“I am jersey”),并且想要将其中的每个单词存储到我的结构中,具体来说,words[0] 存储“I”,words[1]存储“am”,words[2] 存储“jersey.”。然而,我存储在里面的不是一个单词,而是NULL。如何解决这个问题?

此外,在*struct Words * parse_string*函数中,其第三部分似乎也存在一些问题。当我调试它时,缓冲区存储了其中的每个字符,即'I','','a','m',''......正确吗?

我的代码如下所示。

这是我的 .c 文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hwTest.h"


int main(int argc, const char * argv[]) {
    struct words *w1 = NULL;
    int i;
    char *str = "I am jersey.";

    w1 = parse_string(" ", str);

    for(i = 0; i < w1->count; i++){
        printf("  [%d] = \"%s\"", i, w1->words[i]);
        printf("\n");
    }
}

struct words *parse_string(char *delimiter, char *string){
    //first allocate memory space;
    // Head pointer doesn't need to store data, it's used for iterating;
    words *wordsHead = (words *)calloc(1, sizeof(words));
    wordsHead->next = NULL;

    //Second, copy the input *string to the buffer field in struct words;
    strcpy(wordsHead->buffer,string); //这里就出现了问题:存储在buffer中的是‘I’ ‘ ’ ‘a’...

    //Third, use strtok to parse the contents of buffer into up to 10 words, delimited by the character in the string
    int x;
    for(x = 0; x<10; x++){
        char *temp = strtok(wordsHead->buffer, delimiter);
        if(temp == NULL){
            //When we finished, set int x to "words->count"
            wordsHead->count = x;
            break;
        }
        //Store individual word from "words" in "wordHead->words[x]" where x represents the index.
        wordsHead->words[x] = temp;

        // Finally, returns pointers to following words;
        strtok(wordsHead->buffer,NULL); /*pass NULL to 2nd and following calls*/
    }

    return wordsHead;
}

这是我的 .h 文件:

#ifndef hwTest_h
#define hwTest_h


typedef struct words{
    // for a linked list;
    struct words *next;

    //to store the string to be parsed;
    char buffer[128];

    //number of words(up to 10);
    int count;

    //pointers to up to 10 words;
    char *words[10];

} words;

struct words *parse_string(char *delimiter, char *string);



#endif /* hwTest_h */

最佳答案

for(x = 0; x<10; x++){
    char *temp = strtok(wordsHead->buffer, delimiter);
    // ...
    strtok(wordsHead->buffer,NULL); 
}

这是从缓冲区提取 token 的错误方法。将其更改为

char *temp = strtok(wordsHead->buffer, delimiter);
for(x = 0; x<10; x++) {
   // ...
   strtok(NULL, delimiter); 
}

注意strtok的哪个参数变为NULL

关于c - 如何将结构存储为链表节点,并且该结构具有 char *words[10] 这是一个已解析的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58028181/

相关文章:

C语言,解释一下这段代码

c - 使用 HMAC() 函数后释放内存吗?

C int 到 char 不使用 char 格式打印

mysql - 无法连接到现有 MySQL 数据库

c++ - 从 std::string 中删除连续的重复字符

javascript - JavaScript 中的 ' and "有什么区别?

c - 为什么不能直接删除第一个节点(头节点)?

swift - Swift 中的循环链表

c - 指针变量和字符串复制 - C

java - java中链表的迭代和