C语言pointer 和 structure 常用项目级别知识

Pointer

当新建一个指针,但又不想用这个指针修改该变量的内容的时候,应该使用const 关键字

  1. 这个指针只能用来读取该变量,而不能修改该变量的值,防止误操作
  2. 只是无法用这个指针来修改该变量,并不意味着该变量是read only的

通常在指针作为函数输入时考虑使用它

(常见的使用场景是AUTOSAR的各个给user的callback 函数,因为既可以通过指针传递数据,又可以防止用户误操作篡改原数据)

void func ( int a, const int *b)
{
    // this will give an error, so it can avoid user modify the var accidently
    *b = 2;
}


 

Structure

1.  对structure的理解和使用场合

structure 本质是一系列variable的合集,因此在有 a set of related variable definition 的时候,就应该使用structure

2. structure作为函数输入的注意事项

structure 作为函数输入时应该传递其指针而不是本身,原因有两点

  • 传递structure本身相当于把所有元素全部传递给了函数,会占用大量的stack空间。而传递指针则只会传递structure的地址
  • 函数的输入是形参,只有传递指针才能实现对structure元素内容的修改

3. structure的元素包含poiner的示例

// structure type definition
typedef struct{
int a;
int * b;
}EthStatus_Type;

int global_Var;

// variables will be used
EthStatus_Type EthStatus_a;


// example in function call
void func( EthStatus_Type *Var)
{
    // access the int element
    Var->a = 10;

    // access the pointer element
    Var->b = &global_Var;

    // access the pointer element
    *(Var->b) = 11;    
}

func( &EthStatus_a );
  • 传递structure的指针作为函数输入
  • 应用 -> 符号来操作结构体的指针
  • 对结构体内pointer元素的操作和其他普通variable的操作是一模一样的

Structures that contain pointers do not allocate memory to store the data that is pointed to by its members, only the memory to store the addresses.

4. Structure 数组

具体操作就和普通数组一样

    Var->a = 10;

    (Var+1)->a  = 12;
 

// structure type definition
typedef struct{
int a;
int * b;
}EthStatus_Type;

int global_Var;

// variables will be used
EthStatus_Type EthStatus_a[2];


// example in function call
void func( EthStatus_Type *Var)
{
    // access the int element
    Var->a = 10;

    // access the pointer element
    Var->b = &global_Var;

    // access the pointer element
    *(Var->b) = 11;    

    // access the second strcuture
    (Var+1)->a  = 12;
    
}

func( EthStatus_a );

Array of Structures in C - C Programming Tutorial - OverIQ.com

reference:

Structures and pointers in C - DEV Community

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值