无法从char **获取字符串

时间:2014-08-28 17:09:46

标签: c

我在这里使用双字符指针

获得了一个程序
#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

出于某种原因,我不能将字符串传递回main。我究竟做错了什么?首先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

char* pmsg = *message;

您正在每次迭代初始化pmsg,因此它始终指向第一个char,将其放在for循环之前。

答案 1 :(得分:1)

那是因为你有:

    char* pmsg      = *message;

在循环中。 pmsg只指向*message的第一个对象。

更改函数loadarray,以便在pmsg循环之前初始化for

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++;

    }
}