PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 14, 2022

[FIXED] How to Convert a String Array to a Char * Array c++

 September 14, 2022     arrays, c, c++, exec, string     No comments   

Issue

So I want to pass arguments to following function

execve(char *filename, char *argv[], char *envp[])

currently my argv[] is a string array. I want to convert it into a char* array so I can pass it to this function.

I have looked around and found many ways to convert a string to a char array but how to convert a string array to an array of char array I guess would be the right term Any help?


Solution

You'll need to get the address of the data inside your std::strings. Note, that these are not required to be null-terminated, i.e., you'll need to make sure that all strings are null terminated. Also, the array passed as argv also needs to have the last element to be a null pointer. You could use code along the lines of this:

std::string array[] = { "s1", "s2" };
std::vector<char*> vec;
std::transform(std::begin(array), std::end(array),
               std::back_inserter(vec),
               [](std::string& s){ s.push_back(0); return &s[0]; });
vec.push_back(nullptr);
char** carray = vec.data();

When compiling with C++03, there are some changes necessary:

  1. Instead of using the lambda expression, you need to create a suitable function or function object doing the same transformation.
  2. Instead of using nullptr you need to use 0.
  3. In C++03 std::string is not guaranteed to be contiguous, i.e., you need an additional, auxiliary std::vector<char> to hold a contiguous sequence of characters.
  4. There are no functions begin() and end() deducing the size of an array but they can easily be implemented in C++03:

    template <typename T, int Size> T* begin(T (&array)[Size]) { return array; }
    template <typename T, int Size> T* end(T (&array)[Size]) { return array + Size; }
    
  5. The C++03 std::vector<T> doesn't have a data() member, i.e., you also need to take the address of the first element.



Answered By - Dietmar Kühl
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing