【发布时间】:2017-01-31 03:00:01
【问题描述】:
我有一个接受字符串数组的函数。它通过特定字符的存在来分隔所有这些字符串,在本例中为“|”。请参阅我之前的问题以获得更好的想法Split an array of strings based on character
所以,我有一个如下所示的字符串数组:
char ** args = {"ls", "-l", "|", "cd", "."}
我的 parseCmnds 函数应该遍历数组中的每个字符串并创建一个新的字符串数组,其中包含“|”之前的所有字符串特点。然后它创建一个链表,其中每个节点指向我创建的每个字符串数组,本质上将原始字符串数组分离为相互链接的单独字符串数组。
所以,我的解析循环应该创建类似这样的内容:
在第一次迭代中: char ** 命令 = {"ls", "-l", NULL}
第二次迭代 char ** command = {"cd", ".", NULL}
每次迭代后,我的函数都会创建一个新的链表节点并填充它。我根据我在上一个问题中得到的一些答案构建了代码(感谢一百万)。但是由于某种原因,我遇到了一个我无法弄清楚的分段错误。有人可以检查我的代码并让我知道我做错了什么吗?
typedef struct node {
char ** cmnd;
struct node * next;
} node_cmnds;
node_cmnds * parseCmnds(char **args) {
int i;
int j=0;
int numArgs = 0;
node_cmnds * head = NULL; //head of the linked list
head = malloc(sizeof(node_cmnds));
if (head == NULL) { //allocation failed
return NULL;
}
else {
head->next = NULL;
}
node_cmnds * currNode = head; //point current node to head
for(i = 0; args[i] != NULL; i++) { //loop that traverses through arguments
char ** command = (char**)malloc(maxArgs * sizeof(char*)); //allocate an array of strings for the command
if(command == NULL) { //allocation failed
return NULL;
}
while(strcmp(args[i],"|") != 0) { //loop through arguments until a | is found
command[i] = (char*)malloc(sizeof(args[i])); //allocate a string to copy argument
if(command[i] == NULL) { //allocation failed
return NULL;
}
else {
strcpy(command[i],args[i]); //add argument to our array of strings
i++;
numArgs++;
}
}
command[i] = NULL; //once we find | we set the array element to NULL to specify the end
while(command[j] != NULL) {
strcpy(currNode->cmnd[j], command[j]);
j++;
}
currNode->next = malloc(sizeof(node_cmnds));
if(currNode->next == NULL) {
return NULL;
}
currNode = currNode->next; //
numArgs = 0;
}
return head;
}
【问题讨论】:
-
设置错误在代码的什么地方出现?
-
command[i] = (char *)malloc(sizeof(args[i]));-->command[i] = malloc(strlen(args[i]) + 1);--sizeof(args[i])是char *的大小,而不是它指向的字符串的长度。 -
另外...
while(strcmp(args[i],"|") != 0) {应更改为检查args的结尾以及"|"。您要么需要知道args中的字符串数,要么在args的末尾加上NULL来标记结束。
标签: c