我有這個問題,我不明白這是什么意思。我在評論中問我的問題。
int x = 3;
int *y = &x;
int z = *y;
printf("%d", z); //why does this give me the value and not the adress? I thought this means z =*y -> *y =&x -> &x outputs the adress of x
int *u= (y 1); //what does this mean?
printf("%d", *u); //why does this give the output of 3?
uj5u.com熱心網友回復:
y
是一個指向整型變數的指標x
。
int x = 3;
int *y = &x;
因此,取消參考指標y
,您可以直接訪問x
指標指向的變數并提取其值。
因此在這個宣告中
int z = *y;
變數通過使用指向 的指標由變數z
的值初始化。x
y
x
相應地這個陳述
printf("%d", z);
輸出初始化3
變數的值。z
在這份宣告中
int *u= (y 1);
在初始化運算式中有一個帶有指標算術的運算式。該運算式在指標指向的變數(物件)之后具有記憶體中y 1
的型別和點。int *
x
y
u
在此陳述句中取消參考未指向有效物件的指標
printf("%d", *u);
呼叫未定義的行為。
uj5u.com熱心網友回復:
int z = *y;
printf("%d", z);
問:為什么這給了我價值而不是地址?
A: y
指向x
變數。因此,取消對y
指標五的參考 3.*y
是y
指向哪個值的值x
是 3。C 教科書中處理指標的章節對此進行了解釋。
int *u= (y 1);
問:這是什么意思?
- 答: y
指向x
(如前所見)。y 1
指向緊跟int
在記憶體中的那個x
,但這是垃圾,因為在那個地址沒有任何有效的東西,它是一個無效的記憶體地址。
printf("%d", *u);
問:為什么這會給出 3 的輸出?
答:如上所述,u
它沒有指向有效地址,因此您在該地址讀取的值是垃圾,它可以是任何東西。取消參考指向無效記憶體的指標是未定義的行為(谷歌該術語)。
uj5u.com熱心網友回復:
指標存盤地址。
星號*y
取消參考指標以獲取指標指向的值。
#include <stdio.h>
int main ( void) {
int x = 3;
int *y = NULL;
y = &x; // store the address of x in the pointer
// y now points to x
printf ( "address of x: %p\n", (void *)&x);
printf ( "address y points to: %p\n", (void *)y);
printf ( "address of y: %p\n", (void *)&y);
int z = 0;
z = *y; //*y de-references the pointer to get the value at the address
//stored in the pointer.
printf ( "value y points to: %d\n", *y);
printf ( "value of z: %d\n", z);
int *w = NULL;
w = y; // store the address y points to in the pointer w
// w and y now point to x
printf ( "address w points to: %p\n", (void *)w);
printf ( "address of w: %p\n", (void *)&w);
printf ( "value w points to: %d\n", *w);
int array[6] = { 1, 2, 3, 4, 5, 6};
int element = 0;
w = array; // store the address of array in w
// w now points to array
printf ( "address of array: %p\n", (void *)array);
printf ( "address w points to: %p\n", (void *)w);
element = *w;
printf ( "value of element: %d\n", element);
element = *(w 3);
printf ( "value of element: %d\n", element);
element = w[5];
printf ( "value of element: %d\n", element);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/493277.html
上一篇:為什么陣列變數需要星號?