我如何通过传递数组指针并在 Alt.1 中获取所请求的数组引用来使 Alt.1 按预期工作?
struct mystruct
{
int id1;
int id2;
};
const struct mystruct local_struct[] = {
{0, 55},
{1, 66},
};
// Alt.1 i like to make this work (not working)
int get_reference_1(const struct mystruct *s){
s = local_struct;
return 0;
}
// Alt.2 works perfect but i like to use the return as status as in Alt.1.
const struct mystruct *get_reference_2(){
return local_struct;
}
int main()
{
struct mystruct *s = NULL;
// Alt.1
if(get_reference_1(s))
/* Expected Fail*/
else
/* Expected Success*/
// Alt.2
s = get_reference_2()
if(!s)
/* Expected Fail*/
else
/* Expected Success*/
return 0;
}
也许我想错了,我需要传递一个双指针?
编辑:更正为“const”。 Edit2:更新标题。
最佳答案
s = local_struct;
正在更改局部变量 - 它不会更改 main 中的变量。传递变量的地址并对取消引用它的原始变量进行更改。
int get_reference_1(struct mystruct **s){
*s = local_struct;
return 0;
}
调用它会是
if(get_reference_1(&s))
/* Expected Fail*/
else
/* Expected Success*/
您还通过将 const
变量分配给非 const 变量而让编译器报错。这里的 local_struct
是在您的代码中声明的常量 struct
。解决方案检查你是否在做正确的事情——这个分配是否必要?您还可以根据需要添加 const
限定符:
int get_reference_1(const struct mystruct **s){
*s = local_struct;
return 0;
}
...
const struct mystruct *s = NULL;
在最坏的情况下,删除 const
限定符。
关于C const 指向 const struct 数组的指针作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829188/