这些链表指针声明的差异

问题描述 投票:0回答:2

有什么区别

  1. struct LinkedList *current = malloc(sizeof(struct LinkedList));

  1. struct LinkedList *current;

哪里

struct LinkedList{
int data;
struct LinkedList *next;
}

当我创建 LinkedList 时,我无法通过后一个 LinkedList 声明实现大部分预期结果。

c linked-list singly-linked-list
2个回答
3
投票

struct LinkedList *current;
定义了一个名为
current
且类型为
struct LinkedList *
的对象,并且没有为其指定初始值。如果它出现在函数之外,则该对象将被初始化为空指针。如果它出现在函数内部,则它未初始化,并且对象的值是不确定的。

struct LinkedList *current = malloc(sizeof(struct LinkedList));
如上定义了一个名为
current
的对象,调用
malloc
struct LinkedList
类型的对象分配足够的内存,并使用
current
的返回值初始化
malloc
。这通常出现在函数内部,因此
malloc
在程序执行期间执行。

当我创建 LinkedList 时,我无法使用第二个提到的代码实现大部分预期结果。

那是因为

current
没有指向保留内存,因此尝试将其用作指针会造成一些不好的结果。


0
投票

如果定义了一个指针,它就没有地址。但是,如果您将其等于

malloc
,则它在内存中具有该大小的地址,并且您可以用一些数据填充该地址。 如果你在没有
malloc
的情况下使用它并填写它,则会在运行时出现分段错误。

运行此代码查看结果:

#include <stdio.h>
#include <stdlib.h>

struct LinkedList{
    int data;
    struct LinkedList *next;
};

int main(int argc, char const *argv[])
{
    
    struct LinkedList *current = malloc(sizeof(struct LinkedList));
    current->data = 1;
    printf("%d\n", current->data );

    struct LinkedList *current1;
    current1->data = 2;
    printf("%d\n", current1->data );

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.