Use of arrays, pointers, structures

When using the C language to express a set of data with a specific format and order, such as a message. The message data often contains data of different functions. In order to distinguish the sequence and locate the position of the data in the message, we usually use the method of defining the structure to represent the message, such as receiving. If we want to send data, we only need to send it sequentially, and don't care about the specific location. It is more convenient to define an array at this time. In order to take into account these two situations, the problem can be solved by the reasonable use of arrays, pointers, and conversions between structures.


#include <stdio.h>

unsigned char a[2] = {0,1};

typedef struct{
	unsigned char a[10];
	unsigned char b;
	unsigned char c;
}str_TypeDef;

str_TypeDef str;
unsigned char *p = (unsigned char *)&str;
unsigned char d[12];
str_TypeDef *pstr = (str_TypeDef *)&d;

void test(void)
{
	unsigned char *p = &a;
//	*(p+0) =  3;
//	printf("*(p+0) =  %d\r\n", *p);
//	*(p+1) =  4;
//	printf("*(p+1) =  %d\r\n", *(p+1));
	*p  =  3;
	printf("*(p+0) =  %d\r\n", *p);
	*(p+1) =  4;
	printf("*(p+1) =  %d\r\n", *(p+1));
}


int main(int argc, char *argv[])
{

//	test();
//	printf("a[0] = %d\r\n", a[0]);
//	printf("a[1] = %d\r\n", a[1]);
    int i = 0;
    for(; i<10; i++)
    {
    	str.a[i] = i;
    }
    str.b = 55;
    str.c = 66;
   
    for(i = 0; i<12; i++)
    {
    	printf("*p+%d is: %d\r\n", i, *(p+i));	
    }
    for(i = 0; i<12; i++)
    {
    	d[i] = i;
    }
    for(i = 0; i<10; i++)
    {
    	printf("pstr->a[%d] = %d \r\n", i, pstr->a[i]);
    }
    printf("pstr->b = %d \r\n", pstr->b);
    printf("pstr->c = %d \r\n", pstr->c);
	return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325987845&siteId=291194637