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