Reputation: 21
Im completely stuck on how to convert a output from one of my functions of char fileParameters[10][10]
into the format of *argv[]
to pass into another function that expects the same format of argv
. The purpose of this is to pass a file input through the same parser that parses command line input.
I understand argv
is a array of pointers but I'm getting confused as aren't all arrays a pointer to the first element?
So therefore fileParameters[10][10]
is a pointer to a pointer and if take the address using &
then I expected an array of pointers? I've tried everything and whatever I do results in a segfault.
Any nudges in the right direction would be appreciated.
Upvotes: 2
Views: 103
Reputation:
I understand argv is a array of pointers but im getting confused as arent all arrays a pointer to the first element?
No. Arrays can be implicitly converted to a pointer to the first element, but they are not the same thing. You can easily tell by the fact that after char a[10];
, sizeof a
will give 10
rather than sizeof(char*)
. Your char[10][10]
is an array of arrays, not an array of pointers.
You need to convert your array to an array of pointers:
char fileParameters[10][10];
// ...
char *fileParameterPtrs[10];
for (int i = 0; i != 10; i++)
fileParameterPtrs[i] = fileParameters[i];
and then you can pass fileParameterPtrs
to the code that is expecting an array of pointers.
@Vasfed rightly adds that you mentioned "that expects the same format of argv
". This doesn't mean just any array of pointers, it means an array of pointers that is terminated by NULL
. Your original fileParameters
cannot hold any NULL
value, so you will need to add one yourself. If all 10 parameters are filled, this is as simple as changing fileParameterPtrs
's length to 11
and adding one more assignment. If you have some other way of keeping track of how many fileParameters
are used, adjust the code accordingly.
Upvotes: 1