【发布时间】:2012-08-23 21:07:46
【问题描述】:
一直让我困惑的一件事,就是字符指针。 时隔四年,我再次流连于c。
以上面提到的情况为例。为什么char指针会这样?当指针指向任何内容或者它像 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作为地址,如果是的话,为什么在前一种情况下这是不可接受的)!
我想我在这里遗漏了一些东西,但是嘿!你猜怎么了 ?他们告诉我在 SO 中搜索!
编辑:将 char 指针指向的地址提供给 int 指针也不会引发错误!
int8_t* intPtr= (int8_t*)0x80485c8 ; // works without casting too ! I guess addresses are acceptable.
取消引用它将给出一个与字符串的第一个 I 相等的值。这是一个好习惯还是存在任何其他解释来忽略它们的字节位大小分配,例如 int 可以容纳一个 char 等等.. ?
正如 hmjd 指出的那样,“初始化语法”是问题所在!我自己写代码没问题,但是修改别人的代码就麻烦了!
【问题讨论】:
-
很难弄清楚你到底在问什么。指针是一个变量,其值通常是另一个变量的地址。
-
我想我在这里遗漏了一些东西 不错的 C 编程书籍/教程,实际上。你问了很多常见问题。
-
@DavidSchwartz 是的!这也是我的基本想法:) 但是这里发生了什么?
标签: c pointers character function-pointers