链表创建为什么需要使用内存分配?

假如有1000个已经定义的结构体,能否直接创建链表?

(1)这是可以的,但是这样就违背了链表出现的初衷(动态扩展)。

(2)另外,直接在全局定义的结构体,存储在静态存储区;在函数内定义的结构体,存储在栈区;而使用malloc来申请空间的结构体,存储在堆空间中。链表一般都放在堆空间中。


如下面段代码,提前定义了结构体数组,然后串联成类似“链表”的形式。

struct MyStruct
{
	int a;
	struct MyStruct* next;
};

int main(void)
{
	struct MyStruct node[6];
	int k;
	for (int i = 0; i < 5; i++)
	{
		scanf("%d", &k);
		node[i].a = k;
		node[i].next = &node[i + 1];
	}
	node[5].a = 44;
	node[5].next = NULL;
	struct MyStruct* temp = &node[0];
	while (temp!= NULL)
	{
		printf("%d", temp->a);
		temp = temp->next;
	}
	getchar(); getchar(); 
	return 0;
}


你可能感兴趣的:(C/C++基础学习)