访问结构中的指针å˜é‡

时间:2011-05-12 08:43:47

标签: c pointers struct

#define SIZE 9

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

任何人都å¯ä»¥å‘Šè¯‰æˆ‘如何访问“尾巴â€å’Œâ€œå¤´â€ï¼Ÿä½¿ç”¨å˜é‡gsm(gsm应该用作结构å˜é‡è€Œä¸æ˜¯æŒ‡é’ˆï¼‰ã€‚

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:-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