質問1
#include<stdio.h>
void fun(int*p)
{
int a=200;
*p=100;
p=&a;
}
int main()
{
int x=0;
int*ip=&x;
fun(ip);
printf("%d %d\n",x,*ip);
return 0;
}
印刷結果は
以下のとおりです。
質問2
#include<stdio.h>
#include<stdlib.h>
int main()
{
int*p=(int *)malloc(sizeof(int));
*p=100;
printf("%d \n",*p);//100
free(p);
printf("%d \n",*p);//ddddd
*p=200;
printf("%d \n",*p);//200
return 0;
}
印刷結果は次のとおり
です。main
関数が実行されている場合、システムはmain関数のスタックフレームを開き、ポインタpを定義します。pはヒープ領域で開かれたスペースを指します。* p = 100、参照を解除します。ポインタと値100を割り当て、free§の場合、ヒープスペースが解放され、スペースがシステムdddddで埋められ、pポインタがこのスペースアドレスをポイントし、dddddを出力して、* p = 200を実行します。ポインタは引き続きこのスペースを再割り当てして200を出力できます。このポインタは無効なポインタと呼ばれますが、このアプローチは非常に安全ではなく、他のプログラムは続行時にこのスペースにアクセスします。
質問3
#include<iostream>
using namespace std;
class Object
{
private:
int value;
public:
Object(int x=0):value(x){
}
~Object(){
}
static void Show(){
cout<<"Object::Show"<<endl;}
void Print(){
cout<<"Object::Print"<<endl;}
void PrintValue(){
cout<<value<<endl;}
};
int main()
{
Object *op=NULL;
op->Show();
op->Print();
op->PrintValue();
return 0;
}
クラスのstaticキーワードは、thisポインターを置き換えることと同じです。
印刷結果は次のとおりです
。3番目のディスプレイがクラッシュします
。Opが空のオブジェクトを指し、値の初期化がありません。PrintValue関数を呼び出すとクラッシュします。
質問4
#include<iostream>
using namespace std;
class Object
{
private:
int value;
public:
Object(int x=0):value(x){
}
~Object(){
}
static void Show(){
cout<<"Object::Show"<<endl;}
void Print(){
cout<<"Object::Print"<<endl;}
void PrintValue(){
cout<<value<<endl;}
};
int main()
{
Object *op=(Object*)malloc(sizeof(Object));
op->Show();
op->Print();
op->PrintValue();
return 0;
}
印刷結果は次のとおりです。次
の図に示すように、
opが指すヒープスペースを分析し、オブジェクトを作成せずにスペースを作成すると、システムはcdcdcdを埋め、PrintValue関数を呼び出し、cdcdcdを値の値と間違えます。 cdcdcdを出力します
質問5
オブジェクトは、スペースではなく、オブジェクトにのみ値を割り当てることができます
int main()
{
Object *op=(Object*)malloc(sizeof(Object));
Object obj(10);
*op=obj;//写法错误!对象不能给空间赋值
op->Show();
op->Print();
op->PrintValue();
return 0;
}