2014-08-28 50 views
0

我有一個程序在這裏使用雙字符指針無法從字符字符串**

#include <stdio.h> 
#include <stdlib.h> 

void loadarray(char ** message) 
{ 
    int size = 10; 
    *message = (char*)malloc(size * sizeof(char)); 
    int i = 0; 
    char stringarr[10]={"hello"}; 
    char msg_byte; 

    for (i = 0; i < size; i++) 
    { 
     //load stringarr into msg_byte 
     msg_byte = stringarr[i]; 
     char* pmsg  = *message; 
     *pmsg = (char)msg_byte; 
     printf("data location %d is %X\n", i, *pmsg); 
     pmsg++; 

    } 
} 


void main() 
{ 
    char* arr; 
    loadarray(&arr); 
    printf("array = %02X %02X %02X %02X %02X\n", arr[0], arr[1], arr[2], arr[3], arr[4]); 
} 

輸出我是

data location 0 is 68 
data location 1 is 65 
data location 2 is 6C 
data location 3 is 6C 
data location 4 is 6F 
data location 5 is 0 
data location 6 is 0 
data location 7 is 0 
data location 8 is 0 
data location 9 is 0 
array = 00 00 00 00 00 

出於某種原因,我不能只是通過字符串回到主。我究竟做錯了什麼?首先感謝您的幫助。

+1

每日提醒不要投出malloc的返回類型。 – Igor 2014-08-28 17:10:52

+1

感謝您的提醒。我一直認爲我必須。 – user3037484 2014-08-28 17:12:02

+3

每日提醒備份每日提醒與來源。 – 2014-08-28 17:12:53

回答

1
char* pmsg = *message; 

要初始化在每次迭代pmsg,因此它總是指向第一個字符時,for循環之前所說的那樣。

1

那是因爲你有:

char* pmsg  = *message; 
在循環

pmsg只能指向*message的第一個對象。

更改函數loadarray,以便pmsgfor循環之前被初始化。

void loadarray(char ** message) 
{ 
    int size = 10; 
    *message = malloc(size * sizeof(char)); 
    int i = 0; 
    char stringarr[10]={"hello"}; 
    char msg_byte; 

    char* pmsg  = *message; 
    for (i = 0; i < size; i++) 
    { 
     //load stringarr into msg_byte 
     msg_byte = stringarr[i]; 
     *pmsg = (char)msg_byte; 
     printf("data location %d is %X\n", i, *pmsg); 
     pmsg++; 

    } 
}