【发布时间】:2014-10-09 18:27:32
【问题描述】:
我有以下代码。也许我还没有像我应该的那样理解指针算术,但为什么 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;这很糟糕。我认为分配不兼容类型的指针是未定义的行为。 -
@ShafikYaghmour:OP 在指针分配期间混合类型,但这不会改变指针算术行为。尽管它违反了严格的别名。另一个问题是在后续循环迭代中取消引用
int_pointer时触发的越界数组访问。我错过了什么吗? -
@jweyrich 此代码中有两种不同形式的未定义行为,如果不涵盖这些问题,则无法正确回答问题,因为代码不正确。
-
@ShafikYaghmour:没错,说得好。我将撤回我的投票并删除 dup 评论。对你的回答也 +1 :-)
-
char_pointer = int_array;-- 这不仅是未定义的行为,还是违反约束。基本上这是非法的;任何符合标准的编译器都必须发出诊断,尽管许多人(不幸的是,恕我直言)将其设为非致命警告。但是,如果您将其更改为char_pointer = (char*)int_array;,则不再违反约束,但您可能会遇到未定义的行为,具体取决于您使用指针的方式。int_pointer = char_array;也一样,除了你也可能遇到对齐问题。