c - 错误:无法从 '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,我也遇到了同样的错误。
解决方案
错误的原因是您在函数中声明结构。结构声明应该在函数之外,以便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);
}
此外,为避免返回指向自动变量的指针,您应该声明s
为static
. 没有必要制作ptr
静态的。
推荐阅读
- lets-encrypt - Rancher Traefik 和 Lets Encrypt 使用两个域
- angular - 导出 PrimeNG 表中的特定列
- apache-spark - 使用 Kafka + Spark Streaming 恰好一次
- python - 使用变量名将 csv 导入 python
- r - Shiny R:当模式与数据框中的给定字符向量匹配时更新 textInput
- boolean - 我无法获得多布尔运算的正确结果
- c# - 外部表不是预期格式 IIS Web 应用程序问题
- python - 使用 python 在 solr 中突出显示
- html - 响应式多边形(三角形)SVG
- python - Pandas:如何从 CSV 文件中读取特定行