![](/img/trans.png)
[英]Getting a subroutine to return a pointer referencing an array and then dereferencing it in main (in C)
[英]Shouldn't dereferencing a pointer provide the value inside the address that you are referencing to?
我這里的代碼基本上涉及一個指向 3 個整數的一維數組的指針,我只是沒有得到 output 代碼行'printf(“地址 B[0] 的值是:%d\n”,* B);'。 就像不應該取消引用指針 B 為我提供它所引用的地址的值? 我的陳述有問題嗎? 謝謝,output 沒有給我值,而是給了我地址:'))
#include<stdio.h>
#include<stdlib.h>
int main (void){
int B[2][3] = {{2,3,4},{5,6,7}};
int (*p)[3] = B;
printf("Address at B[0] is: %d or %d\n", B, &B[0]);
printf ("Value at address B[0] is: %d\n",*B); /*when I dereference pointer B here, shouldn't it give me
the value, why is it that when I execute the code, it gives still gives me the address?*/
printf("B + 1 = %d\n", B+1);
}
B
不是指針。 B
是三個int
的兩個 arrays 的數組。
當在表達式中使用數組時,除了作為 size of 或一元&
的操作數或作為用於初始化數組的字符串文字外,它會自動轉換為指向其第一個元素的指針。
在printf ("Value at address B[0] is: %d\n",*B);
, B
自動轉換為指向其第一個元素的指針。 所以轉換的結果是&B[0]
。 然后*
取消引用該地址。 由於&B[0]
是B[0]
[0] 的地址, *&B[0]
是B[0]
。
由於B
是三個int
的兩個 arrays 的數組,因此B[0]
是三個int
的數組。 由於它是表達式中使用的數組,不是sizeof
或一元&
的操作數,也不是用於初始化數組的字符串文字,因此它會自動轉換為指向其第一個元素的指針。 該轉換的結果是&B[0][0]
。 這與&B[0]
的地址相同,但類型不同。
然后printf ("Value at address B[0] is: %d\n",*B);
嘗試打印此地址。 但是, %d
用於將int
值轉換為十進制數字,而*B
生成指針,而不是int
。 C 標准未定義此行為。 有時它會打印地址或其中的一部分。
要打印地址,請將它們轉換為void *
並使用%p
打印它們:
printf("Address at B[0] is: %p or %p\n", (void *) B, (void *) &B[0]);
printf ("Value at address B[0] is: %p\n", (void *) *B);
printf("B + 1 = %p\n", (void *) (B+1));
如果你打印**B
,那將顯示第一個元素的值:
**B
中, B
將被轉換為指向其第一個元素&B[0]
的指針,從而產生**&B[0]
。*&B[0]
減少到B[0]
,產生*B[0]
。B[0]
被轉換為指向其第一個元素&B[0][0]
的指針,產生*&B[0][0]
。B[0][0]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.