2

I am trying to revive an in-house CAM application, i.e. get it to compile on a current gcc so I can maintain it. I have 27 years of experience as an occasional C/C++ hack ;-)

The part in question is the command-line core, so no UI. It has a sort of front-end that does some checking and manipulation of its input arguments, and moves them into a new argv, used by execv to switch to 1 of the 2 different executables where the real work is done.

The existing code accounts for 5 different CL options, although from what I've seen only 2 are normally used. When trying to populate the new argv (char* const new_argv[32]) any way other than with a brace-enclosed list in the declaration, the compiler says I can only do it with a brace-enclosed....

I've googled for 2 days with no compelling results. Is there a slick way to do this, or just the ugly brute force way? Is there something seriously wrong with the whole design?

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • See: [How to pass a vector of strings to execv](https://stackoverflow.com/questions/5797837/how-to-pass-a-vector-of-strings-to-execv) – Remy Lebeau Sep 14 '21 at 00:45
  • I'm not sure what you have in mind by "the ugly brute force way". Normally you'd just loop over the array, assigning to each element a pointer to the desired string. Note you will have to drop the `const` from the declaration in order to be able to populate it. – Nate Eldredge Sep 14 '21 at 00:51
  • what do you mean with _the ugly, brute force way_? – Luis Colorado Sep 14 '21 at 15:55
  • Is it possible that you end the sentence _the compiler says I can only do it with a brace-enclosed...._? What does the compiler says to you... does it print a message? Can you edit your question and tell what is the exact message the compiler says? – Luis Colorado Sep 14 '21 at 15:59
  • Good article Remy, thanks. The 'brute force' way I was thinking of was a switch case for all possible arg combinations, and because of scoping, calling exec a different way in each one. Which would be hideous. It didn't occur to me that execv was smart enough to cast the char* to char* const by itself, so @dbush 's answer worked. Thanks to all – Matt Walker Sep 15 '21 at 16:06

1 Answers1

2

Change the type of the array to char *[], then you can assign to each array member before passing it to execv.

This is allowed because a char *[] can be converted to a char * const[] but not a const char *[] or const char * const[]

dbush
  • 205,898
  • 23
  • 218
  • 273