[問題] data的長度是variable,要用什麼方式收?
看板C_and_CPP作者zzss2003 (brotherD)時間6年前發表 (2018/12/22 06:37), 6年前編輯推噓6(6推 0噓 5→)留言11則, 8人參與, 7年前最新討論串1/2 (看更多)
小弟目前在寫socket programming(ap層),收底層UDP送過來的資料。
其中function:
int my_recv_UDP(int s,
void* mem,
int len,
struct sockaddr* from,
int fromlen);
用s來當接口,拿mem來收,收的長度為len,並回傳實際接收的資料數(可能會比你在
len 參數中指定的還要少)
比如:
frameLen = my_recv_UDP(socket, rxBuf, 100, &ra, sizeof(ra))
拿socket來收,並把資料放到rxBuf裡面,放100筆,回傳實際接收的資料數(frameLen可能
少於100,代表這次的frame不到100筆,當然,也有可能下一次的frame超過100筆)
問題:
我想寫一個struct,然後用此struct型別的指標指向rxBuf,這樣我就可以透過這個指標的
資料結構看rxBuf裡面的東西了
比如
typedef struct{
int cmd;
int data[?]; //you don't know the data length
int len;
}rxBuf_s;
rxBuf_s* rxBuf_p = rxBuf;
rxBuf_p->cmd (rxBuf的cmd), rxBuf->data(rxBuf的data), rxBuf_p->len (rxBuf的len)
但...rxBuf裡面data的長度不是固定的啊...Orz,這樣子我沒辦法寫出一個struct...
所以我就想到,我是不是可以"先"把data length給算出來(算得出來),然"後"再把它放到
struct裡,比如:
typedef struct{
int cmd;
int data[lengh]; //this is not allowed in C99 standard
int len;
}rxBuf_s;
然後編譯出來的有問題...
上網查了一下發現,C99不允許結構裡的陣列大小為變數...
這種情況下,我該怎麼辦呢?
PS: 上網查過,發現有在結構裡把array長度給0的作法,如:
typedef struct{
int cmd;
int len;
int data[0]; //define the flexible array member
}rxBuf_s;
但這方法並不適用於我這個情況,因為我只是要創造一個ptr,並沒有要創造一個變數。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.163.216.18
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1545460670.A.A20.html
※ 編輯: zzss2003 (118.163.216.18), 12/22/2018 14:55:18
推
12/22 15:36,
6年前
, 1F
12/22 15:36, 1F
推
12/22 16:16,
6年前
, 2F
12/22 16:16, 2F
推
12/22 23:21,
6年前
, 3F
12/22 23:21, 3F
→
12/24 02:08,
6年前
, 4F
12/24 02:08, 4F
→
12/24 02:08,
6年前
, 5F
12/24 02:08, 5F
推
12/24 13:20,
6年前
, 6F
12/24 13:20, 6F
→
12/24 20:36,
6年前
, 7F
12/24 20:36, 7F
→
12/24 20:37,
6年前
, 8F
12/24 20:37, 8F
推
12/25 10:35,
6年前
, 9F
12/25 10:35, 9F
→
12/25 10:36,
6年前
, 10F
12/25 10:36, 10F
推
01/08 15:24,
7年前
, 11F
01/08 15:24, 11F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):