我有以下的代码。也许我对指针运算的理解不够充分,但为什么 int_pointer 要增加 4 而不是 1?对于 char_pointer ,为什么它不是增加 4 而是 1 呢?
#include <stdio.h>
int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
char *char_pointer;
int *int_pointer;
char_pointer = int_array; // The char_pointer and int_pointer now
int_pointer = char_array; // point to incompatible data types.
for(i=0; i < 5; i++) { // Iterate through the int array with the int_pointer.
printf("[integer pointer] points to %p, which contains the char '%c'\n",
int_pointer, *int_pointer);
int_pointer = int_pointer + 1;
}
for(i=0; i < 5; i++) { // Iterate through the char array with the char_pointer.
printf("[char pointer] points to %p, which contains the integer %d\n",
char_pointer, *char_pointer);
char_pointer = char_pointer + 1;
}
}
输出:
[integer pointer] points to 0xbffff810, which contains the char 'a'
[integer pointer] points to 0xbffff814, which contains the char 'e'
[integer pointer] points to 0xbffff818, which contains the char ' '
[integer pointer] points to 0xbffff81c, which contains the char '
[integer pointer] points to 0xbffff820, which contains the char ' '
[char pointer] points to 0xbffff7f0, which contains the integer 1
[char pointer] points to 0xbffff7f1, which contains the integer 0
[char pointer] points to 0xbffff7f2, which contains the integer 0
[char pointer] points to 0xbffff7f3, which contains the integer 0
[char pointer] points to 0xbffff7f4, which contains the integer 2
char_pointer = int_array;
这是不好的。我认为将不兼容类型的指针赋值给另一个指针是未定义行为。 - user3920237int_pointer
时触发的越界数组访问。我有遗漏什么吗? - jweyrichchar_pointer = int_array;
-- 这不仅是未定义行为,而且是约束违规。基本上是非法的;任何符合标准的编译器都必须发出诊断,尽管许多编译器会(不幸的是,在我看来)将其作为非致命警告。但如果您将其更改为char_pointer =(char *)int_array;
,则不再是约束违规,但根据指针的使用方式,您可能会遇到未定义的行为。对于int_pointer = char_array;
也是同样的情况,只是您还可能遇到对齐问题。 - Keith Thompson