繁体   English   中英

相同的 C 指针显示不同的值?

[英]Same C pointer showing different values?

我正在运行这个程序:

#include<stdio.h>

void main(){
  int num = 1025;
  int *poinTer = &num;
  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 个字节)。

所以你实际做的是:

  1. 在堆栈上创建一个int ( num ) 并赋予它值1025
  2. 在堆栈上创建一个int* ( poinTer ) 并为其分配num的内存地址
  3. 通过sizeof(int)增加指针(无意中指向不同的内存地址),然后将其转换为char*并将其分配给新指针。
  4. 将指向这个新内存地址的字节赋值为65 ( 'A' )。

这可能是你想要做的:

#include<stdio.h>

void main(){
  int num = 1025;
  int *poinTer = &num;
  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM