I have this little source code made to parse a string like string variable I need to use in another project
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { char string[] = "C-AC-2C-3C-BOB"; char* s; char* hand[3]; char* usr; s = (char*) calloc(1, sizeof(char)); hand[1] = (char*) calloc(3, sizeof(char)); hand[2] = (char*) calloc(3, sizeof(char)); hand[3] = (char*) calloc(3, sizeof(char)); usr = (char*) calloc(21, sizeof(char)); s = strtok (string,"-"); hand[1] = strtok (NULL, "-"); hand[2] = strtok (NULL, "-"); hand[3] = strtok (NULL, "-"); usr = strtok (NULL, "\0"); printf("%s:%s:%s:%s:%s\n", s, hand[1], hand[2], hand[3], usr); return 0; }
The problem is that I got these 3C:AC:2C:3C:BOB as the result of printf instead of C:AC:2C:3C:BOB .
------- EDIT -----
Code without memory leaks. The problem remains
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { char string[] = "C-AC-2C-3C-BOB"; char* s; char* hand[3]; char* usr; s = strtok (string,"-"); hand[1] = strtok (NULL, "-"); hand[2] = strtok (NULL, "-"); hand[3] = strtok (NULL, "-"); usr = strtok (NULL, "\0"); printf("%s:%s:%s:%s:%s\n", s, hand[1], hand[2], hand[3], usr); return 0; }
source share