【问题标题】:How the parameter of this 2 type of pointer is different?这2种指针的参数有何不同?
【发布时间】:2020-05-12 10:42:25
【问题描述】:

在这篇文章(Why the result of this code is the same when the arg is different?)中,chg的参数是yay *lol,里面是lol(注意前面没有星号)。但是为什么在这段代码中,它会显示一个错误?

void chg (int *lol) {lol=9;}

int main ()
{
    int a=5;
    int *boi=&a;
    printf ("%d\n", *boi);
    chg (boi);
    printf ("%d\n", *boi);

    return 0;
}

[Error] invalid conversion from 'int' to 'int*' [-fpermissive]

那么,参数中不同的数据类型意味着它的工作方式不同?

【问题讨论】:

  • void chg(int* lol) { lol = 9; }: lol 是一个指针,而您正在将一个 int 分配给一个指针。你可能想要这个:void chg(int* lol) { *lol = 9; }
  • 究竟为什么没有星号?
  • @Jabberwocky @klutt 对不起,如果我的问题有点不清楚,我知道这个页面中的代码需要像@Jabberwocky 所说的那样在lol 前面加上星号,但是为什么在我的另一篇文章中是( stackoverflow.com/questions/61747555/…) 不需要星号?参数是yay *lol,在里面,它必须是lol->val,如果我做它会报错[Error] base operand of '->' has non-pointer type 'yay'?
  • 你混淆了指针、结构和指向结构的指针。阅读 C 教科书中处理指针的章节。简答 (*foo).barfoo->bar 相同,但第一种形式几乎从未使用过。

标签: c function pointers parameter-passing


【解决方案1】:

在函数中你应该这样使用

void chg (int *lol) {
    *lol=9;
}

因为它是指针,所以它保存了一个地址。使用* 符号,您就这么说。转到此地址并分配此值。

你也可以像这样使用你的函数

int main ()
{
    int a=5;
    int *boi=&a;
    printf ("%d\n", *boi);
    chg (&a); //send address of a.
    printf ("%d\n", *boi);

    return 0;
}

像这样。意思是一样的

【讨论】:

  • 是的,但是为什么在我的另一个问题(stackoverflow.com/questions/61747555/…)中,参数是yay *lol,但里面只是lol而不是*lol
  • @LastSecond959 那里一个星号,但你只是看不到它。 lol->val(*lol).val 的简写
  • 因为在这个例子中 void chg (yay *lol) {lol->val=9;} 是一样的 void chg (yay *lol) {(*lol).val=9;} 。在结构中,C 有一个特殊的运算符 ->。不然有点丑
猜你喜欢
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
  • 2013-05-22
  • 2020-07-03
  • 2013-05-30
  • 2013-01-31
  • 1970-01-01
  • 2014-04-05
相关资源
最近更新 更多