我已经得到了这个简单的代码,它使用了Jon Eriksen的书中的指针,我试图编译它,但是当我运行它时,gcc给了我编译和分段错误(core dump)时的警告。关于指针的C代码
#include<stdio.h>
int main(){
int i;
int int_array[5] = {1, 2, 3, 4, 5};
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
unsigned int hacky_nonpointer;
hacky_nonpointer = (unsigned int) int_array;
for(i=0; i < 5; i++){
printf("[hacky_nonpointer] points to %p which contains the integer %d\n", hacky_nonpointer, *((int *) hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(int); // hacky_nonpointer = (unsigned int) ((int *) hacky_nonpointer + 1);
}
printf("\n\n\n");
hacky_nonpointer = (unsigned int) char_array;
for(i=0; i < 5; i++){
printf("[hacky non_pointer] points to %p which contains the char %c\n", hacky_nonpointer, *((char *) hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(char); // hacky_nonpointer = (unsigned int *) ((char *) hacky_nonpointer + 1);
}
}
输出:
command line: "gcc -g -o pointer_types5 pointer_types5.c"
pointer_types5.c: In function ‘main’:
pointer_types5.c:16:24: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
hacky_nonpointer = (unsigned int) int_array;
pointer_types5.c:20:103: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
points to %p which contains the integer %d\n", hacky_nonpointer, *((int *) hacky_nonpointer));
pointer_types5.c:20:47: warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘unsigned int’ [-Wformat=]
printf("[hacky_nonpointer] points to %p which contains the integer %d\n", hacky_nonpointer, *((int *) hacky_nonpointer));
pointer_types5.c:29:24: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
hacky_nonpointer = (unsigned int) char_array;
pointer_types5.c:35:101: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
er] points to %p which contains the char %c\n", hacky_nonpointer, *((char *) hacky_nonpointer));
pointer_types5.c:35:48: warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘unsigned int’ [-Wformat=]
printf("[hacky non_pointer] points to %p which contains the char %c\n", hacky_nonpointer, *((char *) hacky_nonpointer));
command line: "./pointer_types5"
Segmentation fault (core dumped)
some more info about my os:
uname -a : Linux PINGUIN 4.10.0-33-generiC#37-Ubuntu SMP Fri Aug 11 10:55:28 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
在64位系统上,指针的大小通常是64位,而int的大小通常是32位。现在您想一下如何将64位值(指针)放入32位变量中。 –
另外,当使用printf使用%p时,你应该直接使用int_array而不是hacky_pointer – leyanpan
好吧,谢谢你们。我能够使它与你的建议一起工作:我从“unsigned int”更改为“long unsigned int”,这样地址就可以放入变量中,我也可以在printf()函数中从“hacky_nonpointer “(void *)”hacky_nonpointer“。 – IDK