【发布时间】:2018-02-22 11:55:49
【问题描述】:
为什么我第二次调用函数时指针“a”指向正确的位置
因为在对“cr”的第二次函数调用期间,if 块中的语句不会被执行,所以指针“a”是如何记住其先前位置的,即使它不是静态变量
代码:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct heavy{
int data;
struct heavy *nxt;
}ode;
void cr(ode**);
void prin(ode*);
int main()
{
ode*head=NULL;
cr(&head);cr(&head);
prin(head);
getch();
return 0;
}
void cr(ode**p)
{
ode*temp,*a;
temp=*p;
if(temp==NULL)
{
a=(ode*)malloc(sizeof(ode));
a->data=1;
a->nxt=(ode*)malloc(sizeof(ode));
*p=a;
a=a->nxt;
a->nxt=NULL;
}else{
a->data=2;
a->nxt=NULL;
}
}
void prin(ode*head)
{
if(head==NULL)
printf("list is empty");
while(head!=NULL)
{
printf("%d",head->data);
head=head->nxt;
}
}
【问题讨论】:
-
真的,这是你最好的问题吗? ->
why is this code working -
显式忘记会浪费 CPU 周期。不要依赖未定义的行为。
-
请正确缩进您的代码。机器(编译器)可以读取和编译任何东西,但对于人类来说,它需要在将文本块读取为 code 时做出一点sense。
-
在
void cr(ode**p)你应该检查a因为未初始化使用。 -->>a->data=2;。如果temp != NULL会发生什么?
标签: c pointers linked-list