我想确认一下,当我有这样的功能时
int subtract(int a, int b)
{
return a-b;
}
当我调用减法(3,2)而不是指针时,我正在传递值。
谢谢,
是的,你是
int a
表示将整数按值传递给函数int* a
意味着将指向某个整数的指针传递给函数。所以为此
int subtract(int a, int b)
{
// even if I change a or b in here - the caller will never know about it....
return a-b;
}
你这样称呼:
int result = substract(2, 1); // note passing values
用于指针
int subtract(int *a, int *b)
{
// if I change the contents of where a or b point the - the caller will know about it....
// if I say *a = 99; then x becomes 99 in the caller (*a means the contents of what 'a' points to)
return *a - *b;
}
你这样称呼:
int x = 2;
int y = 1;
int result = substract(&x, &y); // '&x means the address of x' or 'a pointer to x'
是的,C 总是按值传递函数参数。要传递指针,您必须指定标识指针类型的星号(星号)。
请记住,即使在指针的情况下, C 也总是按值函数参数传递,在这种情况下,指针的地址实际上是被复制的。
是的,您正在传递值。指针将在类型名称之后和变量名称之前用星号表示。