c - 尽管返回类型定义不同,函数仍返回 Int

标签 c struct

所以我在这里有点困惑。我正在做一个更大的项目,但遇到了一些问题,所以我使用一个简单的结构编写了一个小测试用例:

#include <stdio.h>

typedef struct{
    int property1;
}test;

int main(){
    test testing = getNumber();
    printf("%d",testing.property1);
    return 0;
}

test getNumber(){
    test testing = {2};
    return testing;
}

我要做的就是从 getNumber() 返回的测试结构中读取一个属性。然而,编译器报错如下:

test.c(8) : error C2440: 'initializing' : cannot convert from 'int' to 'test'

所以我的问题是:尽管我指定了测试返回类型,但为什么这个函数试图返回一个 int?我该如何解决?我只是对一些简单的事情视而不见吗?

最佳答案

您缺少原型(prototype):

#include <stdio.h>

typedef struct{
    int property1;
}test;

test getNumber(void); // <<< missing prototype

int main(){
    test testing = getNumber();
    printf("%d",testing.property1);
    return 0;
}

test getNumber(void){
    test testing = {2};
    return testing;
}

关于c - 尽管返回类型定义不同,函数仍返回 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7464214/

相关文章:

特定 ISR 后上下文切换到特定进程

c - 查找多边形内侧的算法

c - Valgrind 报告可能的堆栈溢出 - 这是什么意思?

c - 将 pthreads 用于点积时出现段错误

c - 结构体在 C 语言链表中不起作用

struct - Go中的结构体大小

C# Reflection - 如何为结构设置字段值

python - Cython函数内存泄漏

c++ - 如何实现两个可以相互访问的结构体?

c - ANSI C 中的模拟类