gpt4 book ai didi

c - C 指针中的简单函数与传递值

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:36 25 4
gpt4 key购买 nike

我只想确认当我有这样的功能时

int subtract(int a, int b)
{
return a-b;
}

当我调用 subtract(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 指针中的简单函数与传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com