指针操作!!!!!!
很关键!!!!
怎样让下位机知道上位机传输的一个结构数据??
把结构数据转化为字符传输后,下位机再用同样的结构进行接收!!
受启发http://blog.chinaunix.net/u2/63775/showart_503546.html
关键代码:
/*按字符copy ,用到指针类型转换,结构struct知识,一开始use strcpy(),but the fuction working style is finished //by '\0' ,so can't use. i write a function use the parameter length,and pointer*/
static char * copy_by_char(char * dest,const char *src,int length)
{
char *return_ptr=dest;
for (int i=0; i<length; i++)
{
*dest++ = *src++;
}
return return_ptr;
}
|
源代码:
#include<iostream>
#include<stdlib.h>
using namespace std;
//按字符copy ,用到指针类型转换,结构struct知识,一开始use strcpy(),but the fuction working style is finished //by '\0' ,so can't use. i write a function use the parameter length,and pointer
static char * copy_by_char(char * dest,const char *src,int length)
{
char *return_ptr=dest;
for (int i=0; i<length; i++)
{
*dest++ = *src++;
}
return return_ptr;
}
int main(int argc,char **argv)
{
char str1_array[256];
int str2_array[256];
char *string="communisim==commwealism";
struct my_struct
{
int a;
int b;
char c;
};
struct my_struct A,B;
A.a=1;A.b=2;A.c='Y';
char *p1=(char *)&A;
char *p2=(char *)&B;
cout<<"A: length--"<<sizeof(A)<<endl;
copy_by_char( p2, p1, sizeof(A)); //call function
cout<<"B: length-----------"<<sizeof(B)<<endl;
cout<<"A "<<"A.a = "<<A.a<<" A.b = "<<A.b<<endl;
cout<<"B "<<"B.a = "<<B.a<<" B.b = "<<B.b<<" B.c = "<<B.c<<endl;
/*
*string to char array
*
*/
copy_by_char( str1_array, string,5);
str1_array[5]='\0';
//strcpy(str,(char *)&A);
//str[6]='a';str[7]='\0';
cout<<str1_array<<endl;//show array str1
/*
*struct to int array
*
*/
copy_by_char( (char *)str2_array, p1, 8);//copy A.a,A.b
cout<<"str2_array[1] ="<<str2_array[1]<<endl;//show array str1
return 0;
}
|
out put:
root@qing-laptop:~/programe# ./hello
A: length--12
B: length-----------12
A A.a = 1 A.b = 2
B B.a = 1 B.b = 2 B.c = Y
commu
str2_array[1] =2
|
阅读(853) | 评论(0) | 转发(0) |