[英]cannot convert from 'int *' to 'int'
所以我正在看一個代碼,它應該是一個通過引用傳遞的例子。 這個例子來自這里:
當我編譯它時,我得到的錯誤與“int temp = i”行有關:
錯誤1錯誤C2440:'初始化':無法從'int *'轉換為'int'
另一個錯誤與“j = temp”行有關:
錯誤2錯誤C2440:'=':無法從'int'轉換為'int *'
我猜它與指針有關。 由於我確信這是一個簡單的解決方案,我期待因為沒有更多的指針知識而受到抨擊,但請記住,我正是因為這個原因而正在查看這段代碼!
碼:
#include <stdio.h>
void swapnum(int *i, int *j) {
int temp = i;
i = j;
j = temp;
}
int main(void) {
int a = 10;
int b = 20;
swapnum(&a, &b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
問題在於你的交換功能。 您的交換功能應如下所示:
void swapnum( int *i, int *j ) {
// Checks pre conditions.
assert( i != NULL );
assert( j != NULL );
// Defines a temporary integer, temp to hold the value of i.
int const temp = *i;
// Mutates the value that i points to to be the value that j points to.
*i = *j;
// Mutates the value that j points to to be the value of temp.
*j = temp;
}
...這是因為i
和j
是指針。 請注意,當您調用swapnum
您傳遞的是i
的地址和j
的地址,因此需要指針指向這些內存地址。 要獲取內存地址(指針)的值,必須使用這種花哨的*
語法取消引用它, *i
表示i
指向的 值 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.