有什么区别
struct LinkedList *current = malloc(sizeof(struct LinkedList));
和
struct LinkedList *current;
哪里
struct LinkedList{
int data;
struct LinkedList *next;
}
当我创建 LinkedList 时,我无法通过后一个 LinkedList 声明实现大部分预期结果。
struct LinkedList *current;
定义了一个名为 current
且类型为 struct LinkedList *
的对象,并且没有为其指定初始值。如果它出现在函数之外,则该对象将被初始化为空指针。如果它出现在函数内部,则它未初始化,并且对象的值是不确定的。
struct LinkedList *current = malloc(sizeof(struct LinkedList));
如上定义了一个名为current
的对象,调用malloc
为struct LinkedList
类型的对象分配足够的内存,并使用current
的返回值初始化malloc
。这通常出现在函数内部,因此 malloc
在程序执行期间执行。
当我创建 LinkedList 时,我无法使用第二个提到的代码实现大部分预期结果。
那是因为
current
没有指向保留内存,因此尝试将其用作指针会造成一些不好的结果。
如果定义了一个指针,它就没有地址。但是,如果您将其等于
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;
}