dimanche 22 février 2015

Converting char** to char***

I'm working on converting an array of strings to an array of arrays of strings. I's using "|" as my delimiter. For example, I start out with



{"cat", "test.txt", "|", "tac"};


And I am trying to convert that to this



{{"cat", "text.txt", 0}, {"tac", 0}}


So far, here is my code:



char *** break_commands (char** cmds, int nc) {
//counts the number of delimiters there are
int i, j = 0, k = 1;
for (i = 0; i < nc; i++) {
if (strcmp(cmds[i], "|") == 0) {
j++;
}
}

//finds the position of the start of each delimiter-separated char**
int *pos = (int *) malloc (sizeof(int) * (j + 1));
pos[0] = 0;
for (i = 1; i < nc; i++) {
if (strcmp(cmds[i], "|") == 0) {
pos[k++] = i + 1;
}
}

char ***split_args = (char ***) malloc (sizeof(char **) * (j + 1));

int l = 0;
for (i = 0; i < j; i++) {
//new char** to hold the split char**s
char **str = (char **) malloc(sizeof(char *) * (pos[i+1]-pos[i]-1));

//puts char*s into my newly created char**
for (k = 0; k < (pos[i+1]-pos[i]) - 2; k++) {
str[k] = cmds[i + k];
}

//puts a 0 as the last element of my new char**
str[(pos[i + 1] - pos[i]) - 2] = 0;
}

return split_args;
}


I keep getting a segfault but I'm not sure why. Here is the code I'm using to test:



int main(int argc, char **argv) {
char *args[] = {"cat", "test.txt", "|", "tac"};

char ***broken = break_commands(args, 4);
}

Aucun commentaire:

Enregistrer un commentaire