我在这里使用双字符指针
获得了一个程序#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。我究竟做错了什么?首先感谢您的帮助。
答案 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++;
}
}