星期三, 3月 01, 2017
[ C ] Char to struct轉換
如何用char來傳遞struct的內容?
其實struct在locate空間時是連續的,
只是因為struct有事先宣告說我裡面要有多少int,
或者char,或另外一個struct。
所以可以想像成一個連續空間被切成不同的大小,
因此我只要把char的連續空間,切成和struct一樣的大小分配,
那麼我就可以把struct丟進去char裡面了。
我先宣告一個struct大小的char陣列。
char buf[SIZE];
memset(buf, 0, SIZE);
然後用struct pointer的方式來給一個指向struct大小的位址,
struct USB *mobile;
之後我把buf assign給mobile並且強制的轉型。
mobile = (struct USB *)buf;
這樣我修改mobile的值時,等於直接改到buf裡的內容。
之後我把buf丟去印出內容。
Println(buf);
當然Println是要接收char array,
然後function內宣告個usb的struct pointer來當作是接收轉換的值,
struct USB *temp;
之後把char array強制轉換usb struct,
temp = (struct USB *)buf;
這樣一來temp就可以直接拿buf裡已經分配好的值來用了。
SourceCode
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言