首页 > 解决方案 > 错误:无法从 'func::str' 转换为 'str*'

问题描述

我收到此错误,但我真的不知道为什么。

#include <stdio.h>
static struct str* func(void);
int main(void) {

   return 0;
}
static struct  str* func(void) {
   struct str {
       char arimb1 : 4;
       char arimb2 : 4;
       char arimb3 : 4;
       char arimb4 : 4;
   }s;
   static struct  str * ptr;
   ptr = &s;
   return (ptr);

}

错误是:

return value type does not match the function type  [E0120]
'return': cannot convert from 'func::str *' to 'str *' [C2440]

非常感谢大家!
PS:我正在使用 Visual Studio (Microsoft),但我也尝试过 repl c,我也遇到了同样的错误。

标签: cpointersstruct

解决方案


错误的原因是您在函数中声明结构。结构声明应该在函数之外,以便struct str在两个范围内类型相同。

#include <stdio.h>
struct str {
    char arimb1 : 4;
    char arimb2 : 4;
    char arimb3 : 4;
    char arimb4 : 4;
};
static struct str* func(void);

int main(void) {
    return 0;
}

static struct  str* func(void) {
    static struct str s;
    struct str *ptr;
    ptr = &s;
    return (ptr);
}

此外,为避免返回指向自动变量的指针,您应该声明sstatic. 没有必要制作ptr静态的。


推荐阅读