這個問題在這里已經有了答案: 陣列的地址與第一個元素的地址不同? (3 個回答) 2天前關閉。
我在 C 上嘗試鏈表,當我嘗試列印串列的資料時,它給出了有趣的結果,告訴我串列為空。當我在 main 中列印變數的地址并在函式中列印同一變數的引數地址時,它會給出不同的結果。誰能幫我解釋一下,謝謝!這是代碼:
#include <iostream>
using namespace std;
typedef struct link_node{
int data;
link_node* next;
};
void iter(link_node* head){
link_node* cur = head;
cout<<"The address of head in function: "<<&head<<endl;
while(cur!=NULL){
cur = cur->next;
cout<<cur->data<<' ';
}
}
link_node *create(int a){
link_node* head;
link_node* cur;
head =(link_node*) malloc(sizeof(link_node));
cur = head;
for(int i=a;i<a 10;i =2){
link_node * node = (link_node*) malloc(sizeof(link_node));
node->data = i;
cur->next = node;
cur = node;
}
cur->next = NULL;
return head;
}
int main(){
link_node* head_1 = create(0);
link_node* head_2 = create(1);
link_node* result = (link_node*) malloc(sizeof(link_node));
cout<<"The address of head_1: "<<&head_1<<endl;
iter(head_1);
return 0;
}
這是程式的輸出:
The address of head_1: 0x61ff04
The address of head in function: 0x61fef0
0 2 4 6 8
謝謝!
uj5u.com熱心網友回復:
head和head_1是兩個不同的變數,所以它們有兩個不同的地址。但是這些變數的值也是地址(或指標),并且這些值是相同的。
當您處理指標時,很容易混淆變數的地址和變數的值,因為它們都是指標(但指標型別不同)。
換句話說,所有變數都有地址,但只有指標變數的值也是地址。
試試這個代碼
cout<<"The value of the head pointer: "<<head<<endl;
cout<<"The value of the head_1 pointer: "<<head_1<<endl;
uj5u.com熱心網友回復:
head是一個變數,head_1是另一個變數。這些變數都駐留在記憶體中的不同位置。您正在列印出他們所在的位置。
這些變數恰好都是指標型別,并且這些變數的有效負載將是相同的(鏈表頭的地址)。但是您列印出來的變數的實際位置會有所不同。
uj5u.com熱心網友回復:
函式引數按值傳遞,即進行復制。僅當您將引數宣告為參考時,才會傳遞參考(即無副本)。
考慮以下示例:
#include <iostream>
void foo(int* a) {
std::cout << "value of a: " << a << "\n";
std::cout << "address of a: " << &a << "\n";
std::cout << "a dereference: " << *a << "\n";
}
void bar(int* const& b) {
std::cout << "value of b: " << b << "\n";
std::cout << "address of b: " << &b << "\n";
std::cout << "b dereference: " << *b << "\n";
}
int main(){
int x = 42;
int* ptr = &x;
std::cout << "value of ptr: " << ptr << "\n";
std::cout << "address of ptr: " << &ptr << "\n";
std::cout << "ptr dereference: " << *ptr << "\n";
foo(ptr);
bar(ptr);
}
可能的輸出:
value of ptr: 0x7fff77c582cc
address of ptr: 0x7fff77c582c0
ptr dereference: 42
value of a: 0x7fff77c582cc
address of a: 0x7fff77c582a8
a dereference: 42
value of b: 0x7fff77c582cc
address of b: 0x7fff77c582c0
b dereference: 42
ptr,a并且b都指向同一個int。都具有相同的價值。取消參考它們都會導致相同的int結果,這是x有價值42的。但是,a它是一個副本,ptr并且存盤在不同的地址。因為b是通過參考傳遞的,所以獲取它的地址會產生 的地址ptr。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488655.html
