【发布时间】:2021-09-27 14:45:20
【问题描述】:
我是 C 的新手。两种情况下是否有不同的内存管理,例如第一个将数据存储在堆栈中,而第二个将数据存储在堆中。在第一种情况下,是编译器分配的内存。哪个更好用?
第一密码
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
printf("%d ", (*head).data);
if((*head).next!=NULL){
printLL((*head).next);
}
}
int main()
{
struct Node first, second, third;
first.data = 9;
first.next = &second;
second.data = 3;
second.next = &third;
third.data = 7;
third.next = NULL;
printLL(&first);
return 0;
}
第二个密码
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
printf("%d ", (*head).data);
if((*head).next!=NULL){
printLL((*head).next);
}
}
int main()
{
struct Node* first;
struct Node* second;
struct Node* third;
first = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
first->data = 9;
first->next = second;
second->data = 3;
second->next = third;
third->data = 7;
third->next = NULL;
printLL(first);
return 0;
}
如果有任何资源可以阅读,请发送链接
【问题讨论】:
-
AFAIK;堆上的 malloc 内存中的堆栈上的普通变量和堆栈上的指针。我不知道哪个更快。
标签: c linked-list dsa