2010-08-11 279 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