【问题标题】:For functions that take a pointer parameter, do I pass the address in a call?对于带有指针参数的函数,我是否在调用中传递地址?
【发布时间】:2013-12-11 16:52:00
【问题描述】:

例如:

void Sample_Function(char * ptr){ //Stuff }

void Some_Other_Function(){
    char *p;
    p = malloc(sizeof(char)*5);
    // Is this correct?
    Sample_Function(p);
    // Or this?
    Sample_Function(*p);
}

因为 free() 需要一个地址而不是指向的字节,我猜第一个选项是正确的?

另外,对于返回指针的函数:

// Is this correct?
return p;
// Or this?
return *p;

感谢您的帮助!

【问题讨论】:

    标签: c pointers parameter-passing


    【解决方案1】:

    p 的类型是char*,*p 的类型是char。所以Sample_Function(p) 是一个有效的调用。 如果你的功能是:

    char* Some_Other_Function(){ //things}
    

    那么出于同样的原因,您应该返回 p 而不是 *p

    【讨论】:

      【解决方案2】:

      如果p 是指针,则应将其称为Sample_Function(p);如果a 不是指针,则应将其称为Sample_Function(&a)

      如果一个函数返回一个指针,它返回一个地址,所以你应该使用return p;return &a;

      【讨论】:

      • 那么至少 'a' 应该是 char。
      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 2015-05-19
      • 2014-09-09
      • 2021-07-25
      • 2021-02-19
      • 2020-01-09
      • 2014-06-06
      • 1970-01-01
      相关资源
      最近更新 更多