【发布时间】:2012-10-01 01:23:28
【问题描述】:
我不是最好的指针,所以也许你可以看到我做错了什么。
假设我有一个这样初始化的数组:
char *arrayOfCommands[]={"ls -l", "wc -l"};
我的目标是从这个数组中得到一个名为 char *currentCommand 的数组,该数组查看 arrayOfCommands 的特定单元格并将命令分隔成空格。
我的最终目标是在每个循环上都有一个新的 currentCommand 数组,每个看起来像这样:
First Loop:
currentCommand = [ls][-l]
First Loop:
currentCommand = [wc][-l]
这是我目前的代码:
for (i = 0; i < 2; ++i) {
char str[] = arrayOfCommands[i];
char * currentCommand;
printf ("Splitting string \"%s\" into tokens:\n",str);
currentCommand = strtok (str, " ");
while (currentCommand != NULL){
printf ("%s\n",currentCommand);
currentCommand = strtok (NULL, " ");
}
.
.
.
//Use the currentCommand array (and be done with it)
//Return to top
}
任何帮助将不胜感激! :)
更新:
for (i = 0; i < commands; ++i) {
char str[2];
strncpy(str, arrayOfCommands[i], 2);
char *currentCommand[10];
printf ("Splitting string \"%s\" into tokens:\n",str);
currentCommand = strtok (str, DELIM);
while (currentCommand != NULL){
printf ("%s\n",currentCommand);
currentCommand = strtok (NULL, DELIM);
}
}
我收到此错误:** 分配中的类型不兼容**
它正在谈论我正在传递 strtok 函数的“str”。
【问题讨论】:
-
您确定
strtok()是最佳选择吗?您是否考虑过使用strcspn()或strpbrk()或类似的东西?strtok()是一个危险的函数。如果你在库函数中使用它,你必须记录你这样做,因为使用它,你会对任何在使用strtok()时调用你的函数的人造成严重破坏。并且您还必须注意不要出于同样的原因调用使用strtok()的任何其他函数。一般来说,请避开strtok(),除非有老师在火焰中牵着你的手并强迫你把它们留在那儿寻找strtok_r()。 -
char str[] = arrayOfCommands[i];是什么意思? -
您似乎将字符串、char 数组和指针数组混为一谈。也许作为第一步,您可以编写一些带有单个命令字符串并将其解析为令牌数组的东西。创建一个函数,现在您可以为
arrayOfCommands[]中的每个项目调用一些内容。再三考虑,第一步只需将每个标记打印在单独的行上,然后再尝试构建标记数组。