在C++或C中使用Integer和Char指针?

Fat*_*ğlu -1 c c++ pointers

int *ab = (int *)5656;
cout << *ab; //Here appcrash.


int *ab;
*ab = 5656;
cout << *ab; //These block crashes the app too.
Run Code Online (Sandbox Code Playgroud)

但是如果我写这个,我可以得到指针内容的十六进制值:

int *ab = (int *)5656;
cout << ab; //Output is hex value of 5656.
Run Code Online (Sandbox Code Playgroud)

所以我想问:*是一个带有指针(?)内容的运算符,但为什么在这个(这些)示例应用程序崩溃?

如果我将代码更改为此,我可以使用该运算符:

int a = 5656;
int *aptr = &a;
cout << *aptr; //No crash. 
Run Code Online (Sandbox Code Playgroud)

为什么解除引用运算符(*)带来了char的唯一第一个字符:

char *cptr = "this is a test";
cout << *cptr; // Here output = 't'
cout << cptr; // Here output = 'this is a test'
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 9

int *ab = (int *)5656;
cout << *ab; //Here appcrash.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将指针设置为指向ab地址5656.您知道这个地址是什么吗?不,你没有.你告诉编译器相信你有一个int存在.然后,当您取消引用指针时*ab,您显然发现没有int那里,并且您得到未定义的行为.在这种情况下,您的程序崩溃.

int *ab;
*ab = 5656;
cout << *ab;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你有一个未初始化的指针ab,然后你取消引用int它指向5656指向它.由于它未初始化,因此取消引用它会为您提供未定义的行为.这样想吧.你还没有放入地址,ab所以你不知道它指向的地方.你不能只是取消引用它并希望它指向一个int.

int a = 5656;
int *aptr = &a;
cout << *aptr;
Run Code Online (Sandbox Code Playgroud)

这很好,因为你知道你有一个int值为5656 的对象,你知道它aptr包含该int对象的地址.取消引用完全没问题aptr.

const char *cptr = "this is a test";
cout << *cptr; // Here output = 't'
cout << cptr;
Run Code Online (Sandbox Code Playgroud)

(您的代码使用了不推荐的转换char*,因此我将其更改为const char*.)

字符串文字"this is a test"为您提供包含const chars 的数组.但是,它会经历数组到指针的转换,为您提供指向其第一个元素的指针.由于每个元素都是a const char,所以你得到的指针是a const char*.然后将此指针存储在cptr.

所以cptr指向字符串的第一个元素.取消引用该指针会为您提供第一个元素,它只是字符串的第一个字符.所以你输出t.

I/O库具有特殊的重载,它们将const char*s视为指向一串字符.如果没有,cout << cptr那就打印出来的地址cptr.相反,这些特殊的重载将打印出cptr假定指向的以null结尾的字符数组.