Timeline for How to convert string array to const char **?
Current License: CC BY-SA 4.0
Post Revisions
9 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Jun 1, 2021 at 15:24 | vote | accept | Michael | ||
| May 30, 2021 at 14:16 | comment | added | mediocrevegetable1 |
@Michael I suppose you could create an array of pointers to heap memory and copy everything to that, so the strings pointed to by the char *s will remain as is until you free them. Or just keep it like this and not modify the strings at all after the for loop until res is completely useless.
|
|
| May 30, 2021 at 14:09 | comment | added | Michael | @mediocrevegetable1 thanks I see the risk. But what is the right way? I just want to pass these strings and they will be processed. The problem is I need to pass a const char ** since API limitation.. | |
| May 30, 2021 at 13:49 | comment | added | mediocrevegetable1 | Note that this isn't "converting" the strings, just putting their internal string addresses into the other array. This creates an issue: when the strings have to reallocate and thus possibly change their address as a result, the pointers in the arrays may become dangling pointers. Example: godbolt.org/z/fvob3hfxT | |
| May 30, 2021 at 13:40 | answer | added | songyuanyao | timeline score: 4 | |
| May 30, 2021 at 13:40 | comment | added | mediocrevegetable1 |
You're making copies of the strings with auto instead of auto &, so there may indeed be an issue.
|
|
| May 30, 2021 at 13:40 | comment | added | M.M |
It would improve the question to show a complete program. The answer very much depends on what strings is, what its lifetime is, and what you are going to do with res. and what cnt is
|
|
| May 30, 2021 at 13:39 | comment | added | M.M | the contents of the loop are semanticall incorrect as you fill the array with a bunch of dangling pointers | |
| May 30, 2021 at 13:36 | history | asked | Michael | CC BY-SA 4.0 |