我正在學習C,並且正在編寫一個小程序,用於在指針中打印地址以及地址值。我看到沒有錯誤,只是我的代碼打印語句。但是我在使用指針的時候遇到了一些問題。C:瞭解指針,打印地址失敗
#include <stdio.h>
int main(int argc, char *argv[])
{
char a[] = "Hellow World"; // create an arry
char *ap = a; // create a pointer and set the address to `a`
int i = 0; // create a counter
while (*ap) // while inside the array
{
// print the address and contents of array content
printf("Addr: %x, %c\n", ap, *ap);
ap++; // increment through the array
}
// Crash the program, using an array
for (ap = a, i = 0; i<20; i++){
*(ap+i) = '\0';
}
return 0;
}
編譯:
gcc -Wall -g -o bin/pointer2.c source/pointer2.c
錯誤:
source/pointer2.c: In function ‘main’:
source/pointer2.c:16:3: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘char *’ [-Wformat=]
printf("Addr: %x, %c\n", ap, *ap);
當我嘗試在格式化爲一個字符串,而不是十六進制的我得到這個輸出。
print語句:
printf("Addr: %s, %c\n", ap, *ap);
輸出:
Addr: Hellow World, H
Addr: ellow World, e
Addr: llow World, l
Addr: low World, l
Addr: ow World, o
Addr: w World, w
Addr: World,
Addr: World, W
Addr: orld, o
Addr: rld, r
Addr: ld, l
Addr: d, d
對於地址你能給%p – const
而你正在訪問非法地址因爲sizeof(a)<20 – moeCake