C语言—用结构体指针给数组赋值(结构体指针指向字符串,给字符串赋值)

C 语言 同时被 2 个专栏收录
68 篇文章 4 订阅

数组定义:

char acBuf[sizeof(TRANS_HEAD_S) + sizeof(USER_HEAD_S) + 4] = {0};

结构体定义:              

typedef struct 
{
	int iOne;
	int iTwo;
	int iThr;
}TRANS_HEAD_S;

typedef struct 
{
	int iUser;
}USER_HEAD_S;

1、实现结果:

acBuf[0] = 11
acBuf[1] = 0
acBuf[2] = 0
acBuf[3] = 0
acBuf[4] = 12
acBuf[5] = 0
acBuf[6] = 0
acBuf[7] = 0
acBuf[8] = 13
acBuf[9] = 0
acBuf[10] = 0
acBuf[11] = 0
acBuf[12] = 14
acBuf[13] = 0
acBuf[14] = 0
acBuf[15] = 0
acBuf[16] = 15
acBuf[17] = 0
acBuf[18] = 0
acBuf[19] = 0

2、代码实现:

#include <stdio.h>

typedef struct 
{
	int iOne;
	int iTwo;
	int iThr;
}TRANS_HEAD_S;

typedef struct 
{
	int iUser;
}USER_HEAD_S;

int main()
{
	char acBuf[sizeof(TRANS_HEAD_S) + sizeof(USER_HEAD_S) + 4] = {0};
	TRANS_HEAD_S *pstTransHead = NULL;
	USER_HEAD_S *pstUserHead = NULL;
	int i=0;	
	int *pValue = NULL;
    
    /*pstTransHead指针指向了acBuf的头*/
	pstTransHead = (TRANS_HEAD_S *)acBuf;

	pstTransHead->iOne = 11;
	pstTransHead->iTwo = 12;
	pstTransHead->iThr = 13;

    /*pstUserHead指向了acBuf的第13个字节的头,因为结构体TRANS_HEAD_S是12字节*/
	pstUserHead = (USER_HEAD_S *)&pstTransHead[1];
	
	pstUserHead->iUser = 14;

   /*pValue指向了acBuf的第17个字节的头,因为结构体TRANS_HEAD_S是12字节,USER_HEAD_S是4个字节*/
	pValue = (int *)&pstUserHead[1];

	(*pValue) = 15;

	for(i = 0; i < sizeof(acBuf); i++)
	{
		printf("acBuf[%d] = %d\n", i, acBuf[i]);
	}
	
	return 0;
}

3、对代码【pstUserHead = (USER_HEAD_S *)&pstTransHead[1];】

     的解释——结构体赋值给另一个结构体

#include <stdio.h>

typedef struct
{
	int iA;
	int iB;
	int iC;
}TEST_S;

int main(void)
{
	TEST_S t1,t2;

    /*给t1结构体赋值*/	
	t1.iA = 11;
	t1.iB = 12;
	t1.iC = 13;

    /*t1结构体赋值给t2结构体*/
	t2 = t1;

	printf("t2.iA=%d t2.iB=%d t2.iC=%d\n", t2.iA, t2.iB, t2.iC);
	return 0;
}

 结果显示:t2.iA=11 t2.iB=12 t2.iC=13

4、char类型指针指向int类型数值,取值结果显示

#include <stdio.h>

int main()
{
	int i = 1561;
	char c = 0;
	
	c = (char)i;
	
	printf("i=%d c=%hhu\n", i, c);
	return 0;
}

结果显示是:i=1561 c=25

1561:是

25:是

 

  • 2
    点赞
  • 1
    评论
  • 11
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值