要求:判断程序对错,并对错误的程序进行改正
第一道:
(运行错误)
#include
using namespace std;
void Initiate(int *a)
{
a=NULL;
}
void main()
{
int *a; //声明一个指向int的指针,但是没有初始化,也就是说实参a的地址未知,所以出错
Initiate(a);
}
第二道:
(运行正确)
#include
using namespace std;
void Initiate(int *a)
{
a=NULL;
}
void main()
{
int a; //声明了一个int型的 a,本身占有内存空间
Initiate(&a); //使用&a,实参传入地址
}
第三道:
(运行正确)
#include
using namespace std;
void Initiate(int **a) //由于定义的指针没有具体的内存地址,所以用指向指针的指针对指针赋值地址。
{
*a=NULL;
cout<
}
void main()
{
int *a;
Initiate(&a); //由于用int *a,只是声明了一个指针,但是该指针没有地址,所以用&a传地址
cout<
system("pause");
}
第四道:
(运行错误)
#include
using namespace std;
typedef struct Node
{
char a;
struct Node *next;
}Lnode;
typedef struct Queue
{
Lnode *front;
Lnode *rear;
}LQueue;
void Initiate(LQueue **a)
{
(*a)->front=NULL; //由于(*a)没有地址,所以这一步报错
(*a)->rear=NULL;
cout<
}
void main()
{
LQueue *Q; //声明一个LQueue型指针,本身不占有内存,只是一个指针,没有赋值前,没有地址
Initiate(&Q);//使用&Q企图传入指针的地址
system("pause");
}第五道:
(运行正确)
#include
using namespace std;
typedef struct Node
{
char a;
struct Node *next;
}Lnode;
typedef struct Queue
{
Lnode *front;
Lnode *rear;
}LQueue;
void Initiate(LQueue *a)
{
a->front=NULL; //a具有了地址,那么a->front语句正确
a->rear=NULL;
cout<
}
void main()
{
LQueue Q; //声明一个LQueue型的变量,它本身有内存空间
Initiate(&Q);//使用&Q,实参具有地址
system("pause");
}
第六道:
(运行错误)
#include
using namespace std;
void Destroy(int *a)
{
free(a);
//free()函数与malloc()函数成对出现,程序中没有动态申请空间,所以不能调用free()函数释放int变量a
//a是由操作系统自动释放
}
void main()
{
int a=3;
Destroy(&a);
cout<
system("pause");
}
第七道:
(运行错误)
#include
using namespace std;
typedef struct head
{
int a;
struct head *next;
}NLode;
void intial(NLode **head) //由于声明的指针没有地址,所以使用指向指针的指针,对这个指针进行初始化赋值
{
*head=(NLode *)malloc(sizeof(NLode));//将这个指针指向一段动态开辟的内存,因此指针有了地址
(*head)->next=NULL;//因为有了地址,所以此语句有意义
}
void main()
{
NLode *head1; //声明一个指针
intial(&head1);//实参企图传入指针地址
}