[英]Same C pointer showing different values?
我正在运行这个程序:
#include<stdio.h>
void main(){
int num = 1025;
int *poinTer = #
char *pointChar = poinTer+1;
*pointChar = 'A';
printf("Size of Integer: %d\n", sizeof(int));
printf("Address: %d, Value: %d\n", poinTer, *poinTer);
printf("Address: %d, Value: %c\n", poinTer+1, *(poinTer+1));
printf("Address: %d, Value: %c\n", pointChar, *pointChar);
}
*pointChar 和 *(pointTer+1) 应该输出相同的结果,但我得到的输出不同。 *pointChar 不输出任何值:
Size of Integer: 4
Address: 1704004844, Value: 1025
Address: 1704004848, Value: A
Address: 1704004673, Value:
这里发生了什么事?
当您对指针执行+ 1
时,它不一定会将内存地址增加 1。它会增加sizeof(*ptr)
。
在这种情况下, poinTer + 1
等价于(char*)poinTer + sizeof(int)
。 这实际上使处理数组变得更加容易。
好的老式ptr[i]
是*(ptr + i)
语法糖。 因此,如果您有一个包含 10 个整数的数组, ptr[4]
将指向第 5 个元素而不是距基地址 4 个字节的位置(因为整数通常为 4 或 8 个字节)。
所以你实际做的是:
int
( num
) 并赋予它值1025
int*
( poinTer
) 并为其分配num
的内存地址sizeof(int)
增加指针(无意中指向不同的内存地址),然后将其转换为char*
并将其分配给新指针。65
( 'A'
)。这可能是你想要做的:
#include<stdio.h>
void main(){
int num = 1025;
int *poinTer = #
char *pointChar = (char*)poinTer + 1;
*pointChar = 'A';
printf("Size of Integer: %d\n", sizeof(int));
printf("Address: %d, Value: %d\n", poinTer, *poinTer);
printf("Address: %d, Value: %c\n", (char*)poinTer + 1, *((char*)poinTer+1));
printf("Address: %d, Value: %c\n", pointChar, *pointChar);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.