2

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.

Vasfed
  • 18,013
  • 10
  • 47
  • 53
Tom
  • 21
  • 1
  • 1
    Show us your code please. – STF Feb 07 '16 at 09:14
  • Please post a code example, otherwise it's not quite clear what you do and what fails. – Ruslan Feb 07 '16 at 09:14
  • They're not the same. An array is not a pointer. And array of arrays is not the same as an array of pointers. – Jeff Mercado Feb 07 '16 at 09:20
  • 1
    The problem here is that e.g. `char *[]` will decay to a pointer to a pointer, `char **` (which is why you can use both styles for `argv` arrays), and the array you have is a `char [10][10]` will decay to a pointer to an array `char (*)[10]`, which [is not the same as a pointer to pointer](http://stackoverflow.com/a/18440456/440558). – Some programmer dude Feb 07 '16 at 09:22
  • Possible duplicate of [Array to pointer decay and passing multidimensional arrays to functions](http://stackoverflow.com/questions/12674094/array-to-pointer-decay-and-passing-multidimensional-arrays-to-functions) – n. m. could be an AI Feb 07 '16 at 10:53

1 Answers1

1

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.