我有一个关于使用intptr_tvs. 的问题long int.我观察到递增内存地址(例如通过手动指针算术)因数据类型而异.例如,递增char指针会将1添加到内存地址,而递增int指针会为double添加4,8,为long double添加16等等...
起初我做了这样的事情:
char myChar, *pChar;
float myFloat, *pFloat;
pChar = &myChar;
pFloat = &myFloat;
printf( "pChar: %d\n", ( int )pChar );
printf( "pFloat: %d\n", ( int )pFloat );
pChar++;
pFloat++;
printf( "and then after incrementing,:\n\n" );
printf( "pChar: %d\n", (int)pChar );
printf( "pFloat: %d\n", (int)pFloat );
Run Code Online (Sandbox Code Playgroud)
编译和执行得很好,但XCode给了我警告我的类型转换:"从指针转换为不同大小的整数."
经过一些谷歌搜索和binging(后者还是一个词?),我看到有些人推荐使用intptr_t:
#include <stdint.h>
Run Code Online (Sandbox Code Playgroud)
...
printf( "pChar: %ld\n", ( intptr_t )pChar );
printf( "pFloat: %ld\n", ( intptr_t )pFloat );
Run Code Online (Sandbox Code Playgroud)
这确实解决了错误.所以,我想,从现在开始,我应该使用intptr_t类型转换指针...但是经过一些烦躁之后,我发现我可以通过替换int为long …
#include <stdio.h>
int main(void)
{
int i = 3;
int* j = &i;
printf("%u",j);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该打印出包含整数3的内存块的地址(一个无符号整数)。但我却收到了这个错误
error: format specifies type 'unsigned int' but the argument has type 'int *'- 。
我从各种来源确认:
1.*j指“存储在 j 中的地址处的值”
2.&j指存储指针 j 的内存块的地址。
3. j 包含一个 unsigned int 值,它是 j 指向的内存块的地址。