2013-09-28 91 views
1

我想查看一段代碼,並且有些事情讓我困惑。當在struct中聲明時,char []和char *有什麼區別?

當我們用以下結構:

struct sdshdr { 
     int len; 
     int free; 
     char buf[]; 
    }; 

我們將分配內存是這樣的:

struct sdshdr *sh; 
    sh = zmalloc(sizeof(struct sdshdr)+initlen+1); 

那麼,什麼是char[] & char*之間的差異,當BUFF已經內部結構中聲明?

char[]表示繼續地址?

+0

聲明'焦炭BUF [] =;'不會導致錯誤。 –

回答

1
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); 
+0

我想我明白了,3ks〜 – Drukenme

+0

不客氣,gl! –

4

區別很簡單char buf[]聲明瞭一個靈活的數組; char * buf聲明一個指針。數組和指針在很多方面都不盡相同。例如,你可以在初始化後直接指向一個指針成員,但不能指向數組成員(你可以指定給整個結構體)。

相關問題