Home > database >  How to split char pointer array into two char pointer arrays
How to split char pointer array into two char pointer arrays

Time:05-18

My question is how can I split argv into two parts and store the parts in two variables.

I want my program to get parameters then a delimiter and then again parameters like this:

./program parameter1 parameter2 \: parameter3 parameter4

As you can see, the escaped ':' will act like a delimiter, cutting the array in two parts. Now I want to get a char *arr1[] which will hold parameter1 and parameter2 and another char *arr2[] which will hold parameter3 and parameter4. The parameters can be of different length.

How can I split argv and save the various parameters in two char *[]? In the end I want to access (with my example in mind) arr1[0] and it should have the string parameter1 inside it, and arr1[1] should have the string parameter2 inside it.

Edit: The problem lies in saving the parameters into the two different char *arr[]. I don't know how to do that, because I only know how to initialize an array with a value.

char *arr1[]; !error
char *arr1[10]; works, but what if I have more than 10 parameters?

Thanks in advance!

CodePudding user response:

Don't! These are all pointers. Instead, use pointers - start pointer and end pointer or start pointer and count of element - to represent a "range" inside the source array.

char **arr1 = &argv[1];
char **arr1end = arr1;
while (*arr1end != NULL) {
    if (strcmp(*arr1end, ":") == 0) {
         break;
    }
    arr1end  ;
}
if (arr1end == NULL) { /* handle error - user did not give : argument */ }
size_t arr1cnt = arr1end - arr1;
// Array arr1 has arr1cnt elements.

char **arr2 = arr1end   1;
char **arr2end = arr2;
while (*arr2end != NULL) {
      arr2end;
}
size_t arr2cnt = arr2end - arr2;
// arr2cnt represents arguments after `:`.

for (size_t i = 0; i < arr1cnt;   i) {
      printf("arr1[%zu]=%s\n", i, arr1[i]);
}
for (size_t i = 0; i < arr2cnt;   i) {
      printf("arr2[%zu]=%s\n", i, arr2[i]);
}
  • Related