我正在學習 C 編程中的陣列,這是書中的示例程式之一(該程式與書中的相同,除了最后的 printf 行)。列印 s 的值給了我陣列的基地址(正如預期的那樣)但是當我嘗試在 printf 陳述句中使用 *(value at) 運算子和 s 時,它仍然給我基地址而不是值 1234。為什么我是否需要使用 **s 來獲取值而不是使用單個 * 運算子?
#include <stdio.h>
int main()
{
int s[4][2]={
{1234,56},
{1212,33},
{1434,80},
{1312,78}
};
int i;
for(i=0;i<=3;i )
printf("Address of %d th 1-D array = %u\n", i, s[i]);
printf("%u\n", s);
return 0;
}
#include <stdio.h>
int main()
{
int s[4][2]={
{1234,56},
{1212,33},
{1434,80},
{1312,78}
};
int i;
for(i=0;i<=3;i )
printf("Address of %d th 1-D array = %u\n", i, s[i]);
printf("%u\n", *s);
return 0;
}
uj5u.com熱心網友回復:
s 是一個由 2 個整陣列成的陣列。
所以*s和s[0], s[1], s[2], s[3]都是 2 個整數的陣列。
因此**s和s[0][0], s[0][1], ..., s[3][1]都是整數。
由于在大多數運算式中陣列被轉換為指向第一個陣列元素的指標,因此列印s和*s將給出相同的值。但請注意,它們的型別不同。順便說一句:印刷&s[0][0]也將提供相同的價值。
順便提一句:
要列印指標,請使用%p并將指標轉換為 void-pointer。喜歡:
printf("%p\n", (void*)*s);
uj5u.com熱心網友回復:
因為s是一個二維陣列,s[i]指向一個指標,而指標本身指向一個int值。
如果你修改你的代碼如下,你可以看到實際值:
#include <stdio.h>
int main()
{
int s[4][2]={
{1234,56},
{1212,33},
{1434,80},
{1312,78}
};
int i, j;
for(i=0;i<=3;i ) {
printf("Address of %d th 1-D array = %u\n", i, s[i]);
for(j=0;j<2;j ) {
printf(" Value of %d th element of that array = %u\n", j, s[i][j]);
}
}
printf("%u\n", s);
return 0;
}
實際編制此檔案時,您會收到警告,該插補值:s[i]在第14行,并s在第20行的型別int *和int (*)[2]分別。
$ gcc test.c
test.c:14:52: warning: format specifies type 'unsigned int' but the argument has type 'int *' [-Wformat]
printf("Address of %d th 1-D array = %u\n", i, s[i]);
~~ ^~~~
test.c:20:18: warning: format specifies type 'unsigned int' but the argument has type 'int (*)[2]' [-Wformat]
printf("%u\n", s);
~~ ^
2 warnings generated.
修改后的程式的列印輸出:
$ ./a.out
Address of 0 th 1-D array = 1830793904
Value of 0 th element of that array = 1234
Value of 1 th element of that array = 56
Address of 1 th 1-D array = 1830793912
Value of 0 th element of that array = 1212
Value of 1 th element of that array = 33
Address of 2 th 1-D array = 1830793920
Value of 0 th element of that array = 1434
Value of 1 th element of that array = 80
Address of 3 th 1-D array = 1830793928
Value of 0 th element of that array = 1312
Value of 1 th element of that array = 78
1830793904
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315977.html
