我有一小段源代码,用于测试解析类似于变量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
,而不是C:AC:2C:3C:BOB
,这是printf的结果。-------编辑-----
没有内存泄漏的代码。问题仍然存在。
#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
函数的结果覆盖了那些指针。 - Some programmer dudecalloc
编辑分配的整个部分并不能解决主要问题。 - Arrigo Pierotticalloc()
行,然后重新编译和运行。 - Grijesh Chauhan0
为基础索引的。 - alk