2011-05-12 102 views
2
#define SIZE 9 

struct circ_buff{ 
    char buff[SIZE]; 
    int total = 0; 
    char *tail; 
    char *head; 
} gsm; 

有人能告訴我如何訪問「尾部」&「頭部」?使用變量gsm(gsm應該用作結構變量而不是指針)。在結構中訪問指針變量

回答

4
#define SIZE 9 
struct circ_buff{ 
    char buff[SIZE]; 
    int total; /* you can't initialize this here */ 
    char *tail; 
    char *head; 
} gsm; 

int main() { 
    gsm.total = 0; 
    /* it looks like you're writing a circular buffer, so... set head/tail to the 
    * start of the buffer 
    */ 
    gsm.tail = gsm.buff; 
    gsm.head = gsm.buff; 

/* 
    * gsm.head++;    // increment as you add to the buffer, don't 
    *        // forget to check for overflows 
    * 
    * // Other stuff you might want to do (assuming correct boundary checking) 
    * 
    * *gsm.head = 'G';   // set current head to 'G' 
    * 
    * printf("%c\n", *gsm.head); // print current value of head 
    * 
    */ 
    return 0; 
} 
+0

+1:對於一個很好的答案和對stru的基本目的的一個很好的猜測ct – 2011-05-12 09:05:34

+0

@Paul R:提醒我*方式*在我DOS時期的大部分鍵盤緩衝區中:) – forsvarir 2011-05-12 09:10:04

-1
gsm.tail[INDEX] 

*(gsm.tail) 


int main(int argc, char **argv) 
{ 
    #define SIZE 9 

    struct circ_buff{ 
      char buff[SIZE]; 
      int total; 
      char *tail; 
      char *head; 
    } gsm; 

    strcpy(gsm.buff, "ohaiohai"); 
    gsm.tail = gsm.buff; 
    gsm.head = gsm.buff; 

    printf("%s\n", gsm.buff); 
    printf("%s\n", gsm.tail); 
    printf("%s\n", gsm.head); 

    putchar(*(gsm.tail)); 
    putchar(gsm.head[1]); 

    exit(0); 
} 

輸出:

$ gcc main.c && ./a.out 
ohaiohai 
ohaiohai 
ohaiohai 
oh 
+0

見更新我親愛的朋友 – DipSwitch 2011-05-12 09:07:51

+0

這是一個進步 - -1刪除 – 2011-05-12 09:10:26

+0

也許我應該下一次使用更多的解釋:d – DipSwitch 2011-05-12 09:14:16