У меня есть этот небольшой исходный код, созданный для тестирования синтаксического анализа строки, похожей на переменную string
, которую мне нужно использовать в другом проекте.
#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;
}
Проблема в том, что я получил эти 3C:AC:2C:3C:BOB
в результате printf вместо C:AC:2C:3C:BOB
.
-------РЕДАКТИРОВАТЬ-----
Код без утечек памяти. Проблема остается
#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;
}
strtok
. - person Some programmer dude   schedule 12.08.2013calloc
не решает основную проблему. - person Arrigo Pierotti   schedule 12.08.2013calloc()
, затем скомпилируйте и запустите снова - person Grijesh Chauhan   schedule 12.08.20130
. - person alk   schedule 12.08.2013