gpt4 book ai didi

c++ - 在 C++ 或 C 中使用整数和字符指针?

转载 作者:行者123 更新时间:2023-11-30 18:18:06 26 4
gpt4 key购买 nike

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


int *ab;
*ab = 5656;
cout << *ab; //These block crashes the app too.

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

int *ab = (int *)5656;
cout << ab; //Output is hex value of 5656.

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

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

int a = 5656;
int *aptr = &a;
cout << *aptr; //No crash.
<小时/>

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

char *cptr = "this is a test";
cout << *cptr; // Here output = 't'
cout << cptr; // Here output = 'this is a test'

最佳答案

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

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

int *ab;
*ab = 5656;
cout << *ab;

在这种情况下,您有一个未初始化的指针 ab然后您取消引用以将 5656 分配给 int它指向。由于它未初始化,取消引用它会给您带来未定义的行为。这样想吧。您还没有在 ab 中输入地址所以你不知道它指向哪里。您不能只是取消引用它并希望它指向 int .

int a = 5656;
int *aptr = &a;
cout << *aptr;

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

const char *cptr = "this is a test";
cout << *cptr; // Here output = 't'
cout << cptr;

(您的代码使用了已弃用的 char* 转换,因此我将其更改为 const char* 。)

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

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

I/O 库具有特殊重载,需要 const char* s 并将其视为指向字符串。如果没有,cout << cptr只会打印 cptr 中的地址。相反,这些特殊重载将打印出 cptr 的以 null 结尾的字符数组。假设指向。

关于c++ - 在 C++ 或 C 中使用整数和字符指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com