Reputation: 25
I got a program here using double char pointer
#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]);
}
The output I have is
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
For some reason I can't just pass the string back to main. What am I doing wrong? Thanks for your help first.
Upvotes: 0
Views: 81
Reputation: 206567
That's because you have:
char* pmsg = *message;
in the loop. pmsg
only ever points to the first object of *message
.
Change the function loadarray
so that pmsg
is initialized before the for
loop.
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++;
}
}
Upvotes: 1
Reputation: 41017
char* pmsg = *message;
You are initializing pmsg
on each iteration and therefore it always points to the first char, put it before the for
loop.
Upvotes: 1