我已經得到了這個簡單的代碼,它使用了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