#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int * add(int *, int *);
int add(int, int);
void main() {
int a, b, sum, *z;
cout << "enter the value of a & b";
cin >> a >> b;
z = add(&a, &b);
sum = add(a, b);
cout << "\nthe sum is: " << sum << endl;
cout << "the sum is :" << *z << endl; getch();
}
//.....calling with value.....
int add(int a, int b) {
int s;
s = a + b;
return s;
}
//......calling with address.......
int *add(int *a, int*b) {
int r;
r = *a + *b;
return &r;
}
後爲什麼會給出錯誤的答案:爲什麼叫指針給出錯誤的值
輸出........ A = 70 B = 80值的總和:150有地址之和爲:1208
...但是當我給該程序爲:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int * add(int *, int *);
int add(int, int);
void main() {
int a, b, sum, *z;
cout << "enter the value of a & b";
cin >> a >> b;
sum = add(a, b);
cout << "\nthe sum is: " << sum << endl;
z = add(&a, &b);
cout << "the sum is :" << *z << endl;
getch();
}
//.....calling with value.....
int add(int a, int b) {
int s;
s = a + b;
return s;
}
//......calling with address.......
int *add(int *a, int*b) {
int r;
r = *a + *b;
return &r;
}
它提供了正確的答案。
輸出..... a = 70 b = 80與值的總和爲:150與地址的總和爲:150。
爲什麼?
也請提供一下兩個程序之間的區別,這將有助於我們更好地理解您的問題。 – cmaster
如果我們將r聲明爲全局變量,那麼它將在兩種情況下都起作用。是的,請給出兩個程序之間的區別 – Freedom911
可能的[C++代碼需要說明]的副本(http://stackoverflow.com/questions/18409639/c-code -needs-解釋) –