0

我有以下代码:

#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语言是一种黑魔法吗?或者为什么这是奇怪的行为?

4

1 回答 1

1

在这份声明中

n = createNode(path); 

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

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

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

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

于 2019-11-06T11:06:29.787 回答