我有这个小源代码,用于测试类似于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;
}