我有一个函数,它接受一个字符串数组。它通过特定字符的存在来分离所有这些字符串,这种情况下是'|'。请参见我的先前问题基于字符拆分字符串数组以获得更好的理解。
所以,我有一个看起来像这样的字符串数组:
我的parseCmnds函数的作用是遍历数组中的每个字符串,并创建一个新的字符串数组,其中包含'|'字符之前的所有字符串。然后它创建一个链表,其中每个节点都指向我创建的字符串数组中的每个字符串,从而将原始字符串数组分离为彼此链接的单独字符串数组。
因此,我的解析循环应该像这样创建:例如:
在第一次迭代中: char ** command = {"ls", "-l", NULL}
在第二次迭代中: char ** command = {"cd", ".", NULL}
每次迭代后,我的函数都会创建一个新的链表节点并填充它。我根据之前问题中得到的一些答案构建了代码(非常感谢)。但出于某种原因,我得到了一个无法解决的分段错误。有人可以检查我的代码并让我知道我做错了什么吗?
所以,我有一个看起来像这样的字符串数组:
char ** args = {"ls", "-l", "|", "cd", "."}
我的parseCmnds函数的作用是遍历数组中的每个字符串,并创建一个新的字符串数组,其中包含'|'字符之前的所有字符串。然后它创建一个链表,其中每个节点都指向我创建的字符串数组中的每个字符串,从而将原始字符串数组分离为彼此链接的单独字符串数组。
因此,我的解析循环应该像这样创建:例如:
在第一次迭代中: char ** command = {"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 *
的大小,而不是它所指向的字符串的长度。 - Dmitriwhile(strcmp(args[i],"|") != 0) {
应该改为检查args
的结尾以及"|"
。你需要知道args
中字符串的数量,或者在args
的末尾放置一个NULL
来标记结尾。 - Dmitri