2010-08-11 287 views
2

gcc 4.4.4 c89指針和指針數組指針

我明白指針確定。但是,我正在加緊指針數組和指向指針的指針。

我一直在搞這個代碼片段,並留下了我認爲理解的內容。

非常感謝任何建議,如果我的意見是正確的代碼行?

void increment_ptr() 
{ 
    /* Static char array */ 
    char src[] = "rabbit"; 
    /* pointer to array of pointers to char's - create 6 pointers in this array */ 
    char *dest[sizeof(src)]; 
    size_t i = 0; 

    /* pointer to a char */ 
    char* chr_ptr = NULL; 
    /* pointer to pointer that points to a char */ 
    char** ptr_ptr = NULL; 

    /* chr_ptr pointer now points to the memory location where 'rabbit' is stored. */ 
    chr_ptr = src; 
    /* ptr_ptr points to the first memory address of the pointer array of where dest is stored */ 
    ptr_ptr = dest; 

    /* Deference chr_ptr and keep going until nul is reached 'rabbit\0' */ 
    while(*chr_ptr != '\0') 
     /* deference ptr_ptr and assign the address of each letter to the momory location where 
      ptr_ptr is currently pointing to. */ 
     *ptr_ptr++ = chr_ptr++; 

    /* reset the ptr_ptr to point to the first memory location 'rabbit' */ 
    ptr_ptr = dest; 

    /* Keep going until NULL is found - However, my program never finds it, ends in UB */ 
    while(ptr_ptr != NULL) { 
     /* Dereference what the pointer to pointer is pointing at the memory lcoation */ 
     printf("[ %s ]\n", *ptr_ptr++); 
    } 
} 
+0

這是功課? – PeterK 2010-08-11 11:03:07

回答

7

評論每個部分下面(I沒有提到位是正確的):

/* Static char array */ 
char src[] = "rabbit"; 

此數組不是靜態的 - 它具有auto存儲持續時間。

/* pointer to array of pointers to char's - create 6 pointers in this array */ 
char *dest[sizeof(src)]; 

這是一個指向char的指針數組,不是指向數組的指針。數組的長度是7,因爲sizeof(src)是7(它包含nul字符串終止符)。

/* chr_ptr pointer now points to the memory location where 'rabbit' is stored. */ 
chr_ptr = src; 

更確切地說,它指向的src的第一個字符,這是"rabbit"'r'

/* ptr_ptr points to the first memory address of the pointer array of where dest is stored */ 
ptr_ptr = dest; 

它指向dest數組中的第一個指針。

/* Keep going until NULL is found - However, my program never finds it, ends in UB */ 
while(ptr_ptr != NULL) { 

正確 - 因爲您從未初始化過dest。你可以的dest聲明改成這樣:

char *dest[sizeof(src)] = { 0 }; 

...,它會工作。

+0

什麼是指針? – 2012-12-06 02:31:53

1

的錯誤是,當你分配DESTptr_ptr,這實際上是一個指針未初始化數組字符,經歷它withing while循環將失敗。

/* reset the ptr_ptr to point to the first memory location 'rabbit' */ 
ptr_ptr = dest; 

/* Keep going until NULL is found - However, my program never finds it, ends in UB */ 
while(ptr_ptr != NULL) { 
    /* Dereference what the pointer to pointer is pointing at the memory lcoation */ 
    printf("[ %s ]\n", *ptr_ptr++); 
} 
+0

他在前一個循環中設置了dest的前6個成員的值(第七個仍然未初始化)。 – caf 2010-08-11 11:48:43

+0

你是對的,我錯過了那部分。但他確實還是跳過'\ 0' – 2010-08-11 13:16:31