#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;
int_pointer = char_array;
for(i=0; i < 5; i++) {
printf("[integer pointer] points to %p, which contains the integr %d\n", int_pointer, *int_pointer);
int_pointer = int_pointer + 1;
}
for(i=0; i < 5; i++) {
printf("[char pointer] points to %p, which contains the char '%c'\n", char_pointer, *char_pointer);
char_pointer = char_pointer + 1;
}
}
显示以下错误:
pointer_types2.c: In function ‘main’:
pointer_types2.c:13:17: warning: assignment from incompatible pointer type [enabled by default]
char_pointer = int_array;
^
pointer_types2.c:14:16: warning: assignment from incompatible pointer type [enabled by default]
int_pointer = char_array;
^
答案 0 :(得分:2)
您无法执行此操作,因为char
和int
的存储空间大小不同4
。具体来说,您可以尝试:
char_pointer = (char *)&int_array;
int_pointer = (int *)&char_array;
或
char_pointer = (char *)int_array;
int_pointer = (int *)char_array;
哪个会在没有警告的情况下编译,但结果是:
<强>输出:强>
$ ./bin/juxt
[integer pointer] points to 0x7fff0e89d7d0, which contains the integr 1684234849
[integer pointer] points to 0x7fff0e89d7d4, which contains the integr 101
[integer pointer] points to 0x7fff0e89d7d8, which contains the integr 243914712
[integer pointer] points to 0x7fff0e89d7dc, which contains the integr 32767
[integer pointer] points to 0x7fff0e89d7e0, which contains the integr 243914672
[char pointer] points to 0x7fff0e89d7b0, which contains the char ''
[char pointer] points to 0x7fff0e89d7b1, which contains the char ''
[char pointer] points to 0x7fff0e89d7b2, which contains the char ''
[char pointer] points to 0x7fff0e89d7b3, which contains the char ''
[char pointer] points to 0x7fff0e89d7b4, which contains the char ''
注意: int
指针d7d0
,d7d4
,......的增量,并与字符指针值d7b0
进行比较, d7b1
,...以这种方式交换指针最终会导致它们指向内存中的错误位置。
答案 1 :(得分:2)
它们是不同的类型,你不能这样做
指针只能指向与自身类型相同的对象。因为不同的类型在记忆中有不同的长度。例如,这里,int的长度为4,而char的长度为1.当我们对指针进行一些操作时,这里,+ 1,指针移动的步骤不同,当你想访问存储的数据时可能会导致一些错误那里。
然而在某些情况下,使用指针指向不同类型是安全的,它的高级技能,小心
答案 2 :(得分:0)
您可以通过类型转换修复这些警告:
char_pointer = (char *)int_array;
int_pointer = (int *)char_array;