gpt4 book ai didi

c - 指针初始化成什么?

转载 作者:太空狗 更新时间:2023-10-29 17:17:22 24 4
gpt4 key购买 nike

一直让我困惑的一件事,字符指针。 时隔漫长的四年,我再次徘徊在 c 中。

以上述情况为例。为什么char 指针会以这种方式运行?当 pointee 什么都不指向时,我们如何直接寻址它的内容,或者它就像 char 指针存储地址以外的东西!

#include <stdio.h>
#include <stdlib.h>

int main()
{
char* charPtr="I cant understand why";
int* intPtr=60;


printf("%d\n", intPtr); //displays 60
printf("%p\n", intPtr); // displays the hex value of 60

printf("%s\n", charPtr); // displays the wh0le string
printf("%p\n", charPtr); // displays the start address of the string
return 0;

接下来是 int 指针,它如何接受值 60 以及它存储在哪里?

抛开 char 指针和 malloc,我认为指针的基本思想是获取指向的地址!

为什么会出现这些情况

 *intptr = 60 ; // should be setting the pointee's value to 60
intptr = 60 ; // sets the address

抛出编译错误而

  int* intPtr=60;

在没有得到被指派地址的情况下偷偷溜进来(或者是 60 作为地址,如果是这样,为什么这是 Not Acceptable ,而不是在前一种情况下)!

我想我在这里遗漏了一些东西,但是嘿!你猜怎么了 ?他们告诉我在 SO 中搜索!

编辑:将 char 指针指向的地址提供给 int 指针也不会引发错误!

int8_t* intPtr= (int8_t*)0x80485c8 ; // works without casting too ! I guess addresses are acceptable.

取消引用它会给出一个等于字符串的第一个 I 的值。这是一个好的做法吗?或者是否存在任何其他解释对此忽略了他们的字节位大小分配,例如 int 可以持有一个 char 等等.. ?

正如 hmjd 所指出的,“初始化语法”是问题所在!我自己写代码没问题,但修改别人的代码就出问题了!

最佳答案

How can we directly address the contents of the pointee when it points to nothing or is it like char pointer stores stuffs other than addresses !

认为混淆是初始化语法。这:

char* charPtr="I cant understand why";

不取消引用 charPtr。它相当于:

char* charPtr;
charPtr = "I cant understand why";

两个代码片段都将字符串文字"I cant understand why"的地址存储到charPtr。没有指向任何事情发生的指针的取消引用。任何类型的指针变量只能存储一个地址。

这个:

int* intPtr=60;

intPtr 中存储 60 的地址:没有发生 int 分配或引用。此时不存在 int 变量。编译器应该在这一行发出警告。任何引用 intPtr 的尝试很可能会导致崩溃。

关于c - 指针初始化成什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12174835/

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