简体   繁体   English

如何使用struct const指针作为函数参数来控制struct成员行为?

[英]how to control struct member behavior with struct const pointer as function parameter?

I have a C code, somewhat similar to this: 我有一个C代码,与此类似:

struct st
{
    int *var;
}

void fun(st *const ptr)
{
    // considering memory for struct is already initialized properly.
    ptr->var = NULL; // NO_ERROR
    ptr = NULL; // ERROR, since its a const pointer.
}

void main()
{ 
    //considering memory for struct is initialized properly
    fun(ptr);
}

I dont want to declare int *var as const in the structure definition, so as not to mess with the huge code base. 我不想在结构定义中将int *var声明为const ,以免弄乱庞大的代码库。 Not looking to make any change in the structure definition Is there any way in C, to get an error for the NO_ERROR line ptr->var = NULL; // NO_ERROR 不希望在结构定义中进行任何更改C语言中是否有任何方法可以获取NO_ERROR行的错误ptr->var = NULL; // NO_ERROR ptr->var = NULL; // NO_ERROR ? ptr->var = NULL; // NO_ERROR

只需使用const声明参数,因此ptr是指向const对象的指针:

void fun(const struct st* ptr)

Your declaration makes ptr to be constant, but not the object to which it points. 您的声明使ptr保持不变,但使其不变。 Also don't miss struct keyword 也不要错过struct关键字

void fun(struct st *const ptr);

Instead you should use 相反,您应该使用

void fun(const struct st *ptr);

Such declaration allows to change pointer but not the object to which it points. 这种声明允许更改指针,但不能更改其指向的对象。

Keep this in mind: 请记住以下几点:

  • With type* const ptr , you cannot change the pointer but you can change the pointed data 使用type* const ptr ,您不能更改指针,但可以更改指向的数据
  • With const type* ptr , you can change the pointer but you cannot change the pointed data 使用const type* ptr ,可以更改指针,但不能更改指针数据

So all you need is to replace struct st* const ptr with const struct st* ptr . 因此,您所需struct st* const ptrconst struct st* ptr替换struct st* const ptr const struct st* ptr

Superb! 高超! Thank you so much guys! 十分感谢大家! I did this - void fun(const struct st *const ptr); 我这样做-无效的乐趣(const struct st * const ptr); and I was able to get an error while changing both ptr and ptr->var .. Just what I needed.. 而且我在更改ptr和ptr-> var时都遇到了错误。正是我所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM