c - 如何修复返回指向结构数据的指针的函数中的错误

标签 c

我试图通过指针访问结构类型函数中的数据。当我这样做时,我收到 3 个错误

#79 expected a type specifier
#159 declaration is incompatible with previous "memcmp"

头文件:

typedef struct 
{

   uint8 a[50];

   uint8 b;

   uint8 c;
} get;

.c 文件:

main.c()
{

    get example[3];
    get* example(void)
      {
        uint_8 l_LoopCounter_u8;
        example1_st.a[l_LoopCounter_u8++] = data;
        example.b = data;
        example.c = data;
        return (void*)&example1_st ;
       }
}

最佳答案

这是修复您询问的错误和其他一些错误的代码。 如果没有 MCVE,就很难让它完全发挥作用。 您即将进行一些设计更改,以使该函数适用于任何类型的变量,而不仅仅是全局变量。 创建嵌套函数并不是使局部变量在函数中可访问的好方法。让代码在全局上运行,然后更改为在调用引用变量上运行。 ++ 表示您正在遵循一个更复杂的计划。稍后再做。

get example1_st[3]; // changed to the obviously intended name,
// should fix 'declaration is incompatible with previous "memcmp"'
// made this a global, to keep it accessable from function,
// make the code work, then refactor to have the function work on
// variables via call-by reference parmeters

// avoid nested function definition
get* example(void)
{
    uint_8 l_LoopCounter_u8=0; // init index variable

    example1_st.a[l_LoopCounter_u8] = data; // removed ++, which is unnclear/risky here
    example1_st.b[l_LoopCounter_u8] = data;
    example1_st.c[l_LoopCounter_u8] = data;
    return &example1_st ; // no need to cast to void, type is correct
}

int main(void) //changed to a correct main function head,
// should fix "expected a type specifier"
{

   // note that your main function was functionally empty anyway...

}

注意:
不,我没有测试这段代码。由于 OP 缺乏 MCVE,这将很难。
这是为了帮助解决问题,而不是为未知目的提供工作代码。

关于c - 如何修复返回指向结构数据的指针的函数中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54379485/

相关文章:

c++ - 应该如何从回调函数更新/返回值?

c - 如何解决C中的默认垃圾值?

c++ - 如何使用 gtags -v 创建索引但跳过一些子目录

c - C函数中的 "|"是什么?

使用 '==' 运算符进行转换

从 setuid root C 程序调用脚本 - 脚本不以 root 身份运行

c++ - 线程环基准

c++ - 增加 C/C++ 程序使用的(非堆栈)内存

c - 为什么在创建操作系统时不应该使用库函数?

c - 使用C替换具有更高性能的最佳方法是什么?