我试图通过指针访问结构类型函数中的数据。当我这样做时,我收到 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/