【问题标题】:How do you create a list with a pointer to another link in C?如何创建一个带有指向 C 中另一个链接的指针的列表?
【发布时间】:2021-08-24 00:39:25
【问题描述】:

我一直在努力创建一个新节点,它有一个指向不同类型节点的指针,以及一个指向下一个节点的指针。以下是我的两个结构:

// Frame struct
typedef struct Frame
{
    char* name;
    unsigned int duration;
    char* path;
} Frame;

// Link (node) struct
typedef struct FrameNode
{
    Frame* frame;
    struct FrameNode* next;
} FrameNode;

我尝试创建一个 FrameNode 类型的新节点:

/**
This function creates a new frame.
input: name - the name of the frame we want to create, duration - the duration of the frame we want to create, path - the path of the frame we want to create
output: newFrame - a new frame, that will be added to the end of the list of frames
*/

FrameNode* createFrame(char* name, unsigned int duration, char* path) {
    FrameNode* newFrame = (FrameNode*)malloc(sizeof(FrameNode));
    newFrame->frame = (Frame*)malloc(sizeof(Frame)); // create memory for the Frame* inside of FrameNode*

    strcpy(newFrame->frame->name, name);
    newFrame->frame->duration = duration;
    strcpy(newFrame->frame->path, path);

    return (newFrame);
}

我认为这个问题在某种程度上与 strcpy 有关,但我并不完全确定。我过去用过它,一点问题都没有,所以这很奇怪。谢谢:)

【问题讨论】:

  • 这些语句 fs strcpy(newFrame->frame->name, name); strcpy(newFrame->frame->path, path);调用未定义的行为,因为指针名称和路径具有不确定的值。
  • 无关,我不相信FrameNodeframe 成员需要是动态的。相关,如果您使用的是 POSIX 兼容的实现,strdup 将为您节省一些有关复制这些字符串的步骤。
  • @VladfromMoscow 尝试将其更改为:strncpy(newFrame->frame->name, name, nameSize);新帧->帧->持续时间=持续时间; strncpy(newFrame->frame->path, path, pathSize);无济于事。 nameSize 和 pathSize 是 strlen(name) 和 strlen(path) 的结果,我忘了把它们作为参数放在帖子里了。
  • @RaphDaPingu 对不起。我的意思是 newFrame->frame->name 和 newFrame->frame->path 。您需要为这些指针动态分配内存。
  • @VladfromMoscow 愚蠢的我,谢谢!现在完美运行:)

标签: c linked-list nodes


【解决方案1】:

您没有为字符串分配内存,这会使您的代码中出现未定义的行为。如果你有strdup(),这是一种方法:

/**
This function creates a new frame.
input: name - the name of the frame we want to create, duration - the duration of the frame we want to create, path - the path of the frame we want to create
output: newFrame - a new frame, that will be added to the end of the list of frames
*/

FrameNode* createFrame(char* name, unsigned int duration, char* path) {
    FrameNode* newFrame = malloc(sizeof *newFrame);
    newFrame->frame = malloc(sizeof *newFrame->frame);

    newFrame->frame->name = strdup(name);
    newFrame->frame->duration = duration;
    newFrame->frame->path = strdup(path);

    return newFrame;
}

我重写了自I think you should not cast the return value of malloc() 以来的分配,我相信sizeof-usage 的风格比重复类型名称要好。此外,少括号。 :)

请注意,内存分配可能会失败,因此对于“生产质量”,这至少需要检查一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    相关资源
    最近更新 更多