使用指针将 ASCII 值添加到整数

Adding ASCII value to integer using pointers

我在 C++ 中使用指针。片段如下。

int i=97;
char c='A', &cp=c;
cp+=i;
printf("%d",cp);`

'A'的ASCII是65,那么cp就是97+32就是162。

但我得到的输出是 -94。

可能是什么问题?

cp += i 类似于 cp = cp + i;,其中 cp + i 总和为 162,然后将 162 分配给 char.

将超出范围的值分配给 char 会导致实现定义的行为。

在这种情况下,值减去 256 并赋值为 -94。


然而这段代码看起来并不像带有 char &cp = c; 的 C。更像 C++。嗯嗯

无论您考虑什么,指针都是不同的东西。指针可以指向一个地址,而该地址不能由用户作为常量分配。它只能是任何变量的地址。您提供的声明无效。例如

int a=10;
int * b = &a;  // pointing b to a's address 
int * c;       // pointer pointing to nothing
c = &a;        // pointing c to a's address
printf("%d = %d = %d",a, *b, *c);  //pointer value is accessed by *varilable name
*c = 20;       // changing value of a 
printf("%d =%d = %d", a, *b, *c);   // will print 20 =20 = 20
c=20;    //invalid statement because we can not assign address as constant
c=c+1;   // valid statement and increment address by sizeof(int)