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

ответ

7

Комментарии ниже каждой части (биты я не упомянул правильно):

/* 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)]; 

Это массив указателей на символ, а не указатель на массив. Длина массива равна 7, потому что sizeof(src) равен 7 (он включает в себя нулевой ограничитель строк).

/* 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

Что такое указатель? –

1

Ошибки при назначении Dest к ptr_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

Он устанавливает значения первых 6 членов 'dest' в предыдущем цикле (седьмой остается неинициализированным, хотя). – caf

+0

Вы правы, я пропустил эту часть. Но он действительно все еще пропускает '\ 0' –

Смежные вопросы