链表:C: 不存储我要查找的值

linked List: C: does not store the values I am looking for

我有以下代码:

#include <dirent.h>
#include <stdio.h>
#include <string.h>

typedef struct stringData {
    char *s;
    struct stringData *next;
} Node;

Node *createNode(char *s) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->s = s;
    newNode->next = NULL;
    return newNode;
}


void insert(Node **link, Node *newNode) {
    newNode->next = *link;
    *link = newNode;
}

void printList(Node *head) {
    while (head != NULL) {
        printf("%s\n", head->s);
        head = head->next;
    }
}


void listFilesRecursively(char *path, char *suffix);


int main()
{
    // Directory path to list files
    char path[100];
    char suffix[100];

    // Suffix Band Sentinel-2 of Type B02_10m.tif

    // Input path from user
    printf("Enter path to list files: ");
    scanf("%s", path);
    printf("Enter the bands ending: ");
    scanf("%s", suffix);

    listFilesRecursively(path, suffix);

    return 0;
}

int string_ends_with(const char * str, const char * suffix)
{
    int str_len = strlen(str);
    int suffix_len = strlen(suffix);

    return 
        (str_len >= suffix_len) &&
        (0 == strcmp(str + (str_len-suffix_len), suffix));
}

/**
 * Lists all files and sub-directories recursively 
 * considering path as base path.
 */


void listFilesRecursively(char *basePath, char *suffix)
{
    char path[1000];
    struct dirent *dp;
    DIR *dir = opendir(basePath);
    //node_s *head, *first, *temp=0;
    //head = malloc(sizeof(node_s));
    Node *head = NULL;
    Node *tail = NULL;
    Node *n;


    // Unable to open directory stream
    if (!dir)
        return;

    while ((dp = readdir(dir)) != NULL)
    {


        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            //printf("%s\n", dp->d_name);

            // Construct new path from our base path
            strcpy(path, basePath);
            strcat(path, "/");
            strcat(path, dp->d_name);

            if (string_ends_with(path, suffix))
            {
                n = createNode(path);
                insert(&head, n);
                tail = n;   
                printf("%s\n", path);
            }
            listFilesRecursively(path, suffix);
        }
    }

    //printList(head);

    closedir(dir);
}

目的是将递归搜索的值存储在目录中的链表中。我为指向链表的下一个元素的字符串数据创建了节点结构。我还添加了一些功能来插入新数据并指向下一个。最后,我能够通过调用 printLIst 函数打印出链表的值。但是,当我停用调用 printList 函数的第 109 行时,第 103 行中打印的值是正确的。如果我注释第 103 行,并使用存储在我的链接列表中的值调用 printLIst 函数,则会出现一个文件列表,其值与第 103 行中打印的值完全不同。

C 语言中有什么黑魔法吗?或者为什么会出现这种奇怪的行为?

在此声明中

n = createNode(path); 

您正在每个节点中存储指向同一个本地数组 path 的指针。参见函数的定义 createNode

Node *createNode(char *s) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->s = s;
    newNode->next = NULL;
    return newNode;
}

所以至少由于这个错误,程序有未定义的行为。

您应该复制传递的字符串,而不是仅仅将指向它的指针分配给数据成员 s