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

我有以下代码:

#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);
}

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

在C中是一种黑魔法吗?或为什么这种奇怪的行为?

yl987987 回答:链表: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

本文链接:https://www.f2er.com/3152856.html

大家都在问