Search code examples
cpointersstrtokcharacter-arrays

Confused: Pointers and character arrays in C


I'm new to C and trying to split a character array (which I receive from a Serial Port in Ardunio). I looked up some tutorials and came up with this. Help me debug it please.

char action[10];
unsigned long duration;

void split(char input[20])
{
 char *param, *ptr;

 param = strtok_r(input, "#", &ptr);
 action = *param;                      // Need help with this line

 param = strtok_r(NULL, "!", &ptr);
 duration = (unsigned long) *param;    // Need help with this line
}

From what I understand, strtok_r returns a pointer to the character right after the delimiter(#). So if I wanted action[] to be a subset character array of input[] till the delimiter, what should I do?

Edit: Input is something like this: "left#1000!"


Solution

  • It looks like your first token is a string, and the second token is a long. You can use strncpy to copy param into action, and then strtoul to parse an unsigned long to duration.

    param = strtok_r(input, "#!", &ptr);
    strncpy(action, param, sizeof(action));
    // Force zero termination
    action[sizeof(action)-1] = '\0';
    
    param = strtok_r(NULL, "#!", ptr);
    duration = strtoul(param, &param, 10);