-
string to pointer array
I have the following array of pointers:
Code:
const char *arr1[] = {"Test 1","Test 2",};
const char *arr2[] = {"Test 3","Test 4","Test 5",};
There can be arr1, arr2.........arrN. Then I have an integer R that is incremented in the for loop. Based on the R number I want to call
a function my_funct(arr.R). So if R = 1 I would call my_funct(arr1) if R = 2 then my_funct(arr2) and so on. The problem is that there can be any number of the arrN pointers and my program would take a lot of space putting If statements for each R. I would like to create a string with the R number and then convert it to the pointer array before calling my_func() so that I would get my_funct(arr.R) where arr.R would be pointer array and not a string. Can anybody help me.
Luke
-
Like this perhaps?
Code:
#include <stdio.h>
void foo ( const char *argv[] ) {
printf( "First test is %s\n", argv[0] );
}
int main(void)
{
const char *arr1[] = {"Test 1","Test 2",};
const char *arr2[] = {"Test 3","Test 4","Test 5",};
const char **all[] = { arr1, arr2 };
int i;
for ( i = 0 ; i < 2 ; i++ ) foo( all[i] );
return 0;
}
-
It works as expected, Thanks. I wonder what is that extra '*' in all, array of pointers to array pointers?
Luke
-
red is because that is what each thing is a pointer to
green is because an array name by itself is a pointer to the first element of the array ( arr1 == &arr1[0] )
blue because there are multiple elements to be initialised.
-
Of course, you then face the problem of knowing how long each sub-array is.
-
but how do you refer to other elements in the sub array? *all[0] prints the first string of arr1 and *all[1] prints the first string of arr2
-
Array syntax. all[0][1] prints the second string in the first subarray.
-
> Of course, you then face the problem of knowing how long each sub-array is.
Probably like this
Code:
const char *arr1[] = {"Test 1","Test 2",NULL};
The argv and envp pointers passed to main() are like this.