注:文章内容来源于网络,真实性有待确认,请自行甄别。
一段有关函数变量的生存时间的程序#include<stdi
发表于:2024-10-24 00:00:00浏览:7次
问题描述:#include <std.h>
#include <stdlib.h>
struct linked_list
{
int number;
struct linked_list *next;
};
typedef struct linked_list node;
int main(int argc, char *argv[])
{
node *head;
void create(node *p);
int count(node *p);
void #include <std.h>
#include <stdlib.h>
struct linked_list
{
int number;
struct linked_list *next;
};
typedef struct linked_list node;
int main(int argc, char *argv[])
{
node *head;
void create(node *p);
int count(node *p);
void print(node *p);
node *insert(node *head);
head=(node *)malloc(sizeof(node));
create(head);
printf("\n");
print(head);
printf("\n");
printf("\nNumber of items = %d \n",count(head));
system("PAUSE");
return 0;
}
void create(node *list)
{
printf("Input a number\n");
printf("(type -999 at end): ");
scanf("%d",&list->number); /* create current node */
if(list->number==-999)
{
list->next=NULL;
}
else /*create next node*/
{
list->next=(node *)malloc(sizeof(node));
create(list->next); /*recursion occurs*/
}
return;
}
void print(node *list)
{
if(list->next!=NULL)
{
printf("%d-->",list->number); /* print current item */
if(list->next->next==NULL)
printf("%d",list->next->number);
print(list->next); /* move to next item */
}
return;
}
int count(node *list)
{
if(list->next==NULL)
return 0;
else
return(1+count(list->next));
}
书上说函数内的自动变量在函数调用结束后就被释放了,既然如此,为什么在本程序中(有关链表的创建和链表内容的打印,程序本身完全正确,在DEVC++下测试通过)create(head)函数调用结束后,还能用print(head)函数打印出用create()函数创建的链表内容?
c语言为数据分配内存空间的方式大体有两种,一种是分配在栈上,一种是分配在堆上。
分配在栈上的数据有:值传递的参数 非静态的局部变量 等等,他们会随着函数调用的结束被释放。
分配在堆上的数据有:由malloc分配的数据空间 等,他们不会随着函数调用的结束被释放。
更详细的解释可以在网上搜索关键字:c 内存分配
这要涉及到 操作系统 数据结构 方面的知识
猜你喜欢
- 提问c++的问题#include"iostream.h"void
- #include"tream.h" void main() {int k=0; char c='A'; do{switch(c++) {case'A':k++;break; case'B':k--; case'C':k+=2;break; case'D':k=k%2;continue; case'E':k=k*10;break; /3;} k++;} while(c<'G');cout<<"k=...
栏目分类全部>