I am trying to parse a string in to an array with specific delimiters but its not working as expected. I tried a lot to get this working but failed.
Code i am using is below.
CODE TO PARSE
char itemCode[] = "0xFF,0xAA,0xBB,0x00,0x01,0x04,0x90";
char itemCodeToSend[34] = {0};
char ** res = NULL;
char * p = strtok (itemCode, ",");
int n_spaces = 0, i;
/* split string and append tokens to 'res' and 'itemCodeToSend' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p; // Copying to char**
strcpy(&itemCodeToSend[0],p);// Copying to Array
p = strtok (NULL, ",");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces); ++i)
printf ("res[%d] = %s\n", i, res[i]);
for (i = 0; i < 34; ++i)
printf ("0x%02x",(unsigned)res[i]&0xffU);
/* free the memory allocated */
free (res);
I am getting the below output for char** but not for char[]
res[0] = "0xFF"; itemCodeToSend[0] = "0x30";
res[1] = "0xAA"; itemCodeToSend[1] = "0x30";
res[2] = "0xBB"; itemCodeToSend[2] = "0x30";
res[3] = "0x00"; itemCodeToSend[3] = "0x30";
res[4] = "0x01"; itemCodeToSend[4] = "0x30";
res[5] = "0x04"; itemCodeToSend[5] = "0x30";
res[6] = "0x90"; itemCodeToSend[6] = "0x30";
Am i using right way to copy the extracted value to array?
0x30= ASCII for "0", if this helps you debug.exit(-1).itemCodeToSendto represent the hex values in your string you need to somehow parse them (strtolas suggested below,sscanfmight do aswell). At the moment you are just copying the first char (which is always a "0" cause all your entries start with "0x").0xfor your hexa:printf("%#02x", ...).