【发布时间】:2012-01-23 02:21:42
【问题描述】:
我希望我的程序做的是从用户读取输入文本,将该字符串标记为空格作为分隔符,并将每个标记存储在一个 char* 数组中,然后将其返回。
这是我试图使其正常工作的代码的 sn-p:
typedef char* String;
String* split(char* cmd)
{
char* param;
char tmp[128];
String* result = (String*) malloc(10*sizeof(String));
memset(result,NULL,10);
strcpy(tmp,cmd);
param = strtok(tmp," ");
int index = 0;
while(param && index < sizeof(result) / sizeof(*result))
{
result[index] = (char*) malloc(strlen(param));
strcpy(result[index],param);
param = strtok(NULL," ");
index++;
}
}
其中 cmd 是我要标记的字符串,result 是包含每个标记的数组。
当尝试使用简单的 for 循环遍历返回的结果时,此 sn-p 会导致错误(出现分段错误)
String* splittedCmd = split(command);
int i;
for(i=0;i<10;i++)
{
if(splittedCmd[i] != NULL)
printf("%s\n",splittedCmd[i]);
}
【问题讨论】:
-
考虑局部变量和生命周期。想想动态分配,以及为什么你没有它。考虑改用
strncpy。考虑将其标记为“家庭作业”。并考虑切换到 C++。