[英]in C addresses do not work in functions , why is that?
When trying to use a C++ style in C:尝试在 C 中使用 C++ 样式时:
void square(int &x){
x = x * x;
};
This gets an error.这会出错。 error: expected ';', ',' or ')' before '&' token
错误:在“&”标记之前需要“;”、“、”或“)”
i'm most comfortable with c++, but i'm learning C, is there a way to to have adressess in void functions我最喜欢 c++,但我正在学习 C,有没有办法在 void 函数中获取地址
Tried switching from void -> int, double, char.尝试从 void -> int、double、char 切换。 It only works when i take away the & symbol, but i would like to have an address there.
它只有在我去掉 & 符号时才有效,但我想在那里有一个地址。 Is there a way to do that?
有没有办法做到这一点? Should i just use * instead of &, like this:
我应该只使用 * 而不是 &,像这样:
void square(int *x){
x = (*x) * (*x);
};
C language does not have C++ references. C 语言没有 C++ 引用。 You need to use pointers
你需要使用指针
void square(int *x)
{
*x = *x * *x;
}
Your second code is invalid as you assign a local pointer with integer converted to pointer.您的第二个代码无效,因为您分配了一个本地指针,其中 integer 转换为指针。
Even in C++ the sign &
does not denote an address in a declaration.即使在 C++ 中,符号
&
也不表示声明中的地址。 It denotes a reference.它表示引用。
This declaration in C++本声明在C++
void square(int &x){
//...
}
means that the function accepts its argiment by reference.表示 function 通过引用接受其参数。
In C passing by reference means passing an object indirectly through a pointer to it.在 C 中,通过引用传递意味着通过指向它的指针间接传递 object。 So dereferencing a pointer within a function you get a direct access to the original object passed to the function through the pointer.
因此,取消引用 function 中的指针,您可以直接访问通过指针传递给 function 的原始 object。
So this function in C++所以这个 function 在 C++
void square(int &x){
x = x * x;
}
accepts an object of the type int
by reference.通过引用接受
int
类型的 object。
In C this function在 C 这个 function
void square(int *x){
*x = *x * *x;
}
accepts an object of the type int
by reference indirectly through a pointer to it.通过指向它的指针间接引用接受 object 类型的
int
。
Pay attention to that the assignment statement in the second function注意第二个function中的赋值语句
void square(int *x){
x = (*x) * (*x);
}
is incorrect.是不正确的。 You are trying to assign an integer expression to a pointer.
您正在尝试将 integer 表达式分配给指针。 You have to write
你必须写
*x = *x * *x;
as already shown above.如上所示。 That is you need to change the passed object of the type
int
to the function indirectly through a pointer to it.那就是你需要通过指向它的指针间接地将传递的 object 类型的
int
更改为 function 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.