[英]What's the difference between char[] & char* when declare inside struct?
我試圖查看一段代碼,這讓我感到困惑。
當我們使用以下結構時:
struct sdshdr {
int len;
int free;
char buf[];
};
我們將這樣分配內存:
struct sdshdr *sh;
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
那么,當在結構內部聲明buff時, char[]
和char*
有什么區別?
char[]
是繼續地址嗎?
區別在於簡單的char buf[]
聲明了一個靈活的數組; char * buf
聲明一個指針。 數組和指針在許多方面都不同。 例如,您可以在初始化后直接分配給指針成員,但不能分配給數組成員(可以分配給整個結構)。
struct sdshdr {
int len;
int free;
char buf[];
};
struct shshdr *p = malloc(sizeof(struct shshdr));
+---------+----------+-----------------+
p --> | int len | int free | char[] buf 0..n | can be expanded
+---------+----------+-----------------+
struct sdshdr {
int len;
int free;
char *buf;
};
struct shshdr *p = malloc(sizeof(struct shshdr));
+---------+----------+-----------+
p --> | int len | int free | char* buf | cannot be expanded, fixed size
+---------+----------+-----------+
|
+-----------+
| |
+-----------+
在第一種情況下,這是有效的:
struct shshdr *p = malloc(sizeof(struct shshdr)+100); // buf is now 100 bytes
...
struct shshdr *q = malloc(sizeof(struct shshdr)+100);
memcpy( q, p, sizeof(struct shshdr) + 100 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.