-2

Hi I'm looking for copying multidimensional char array into char *string I'm able to copy multidimensional char array into std::string result.

string result;

for (int i=0; i < key; i++)
    for (int j=0; j < text.length(); j++)
        if (rail[i][j]!='\n')
            result.push_back(rail[i][j]);`

Same I want to copy the 2D char array data into char *string

john
  • 71,156
  • 4
  • 49
  • 68
stack_
  • 15
  • 2
  • 7

3 Answers3

0

you can get the char* string from the C++ string object. There is a function c_str() which returns the C string from the C++ string.

vinodsaluja
  • 339
  • 2
  • 14
0

If a char *string means a c-style string (i.e. an array of char characters), then you need to keep track of the the latest position (index in the code below), and set each character in turn. This is if you want to avoid copying. Otherwise, construct the string first, then use c_str(), as other answers have stated.

#include <vector>
#include <iostream>
using std::vector;

#include <string>
using std::string;

int main() {
    const int key = 2;
    string text = "ab";
    string rail[2] = {text, text};

    char result[key * 100];
    int index = 0;
    for (int i=0; i < key; i++)
        for (int j=0; j < text.length(); j++)
            if (rail[i][j]!='\n')
                result[index++] = rail[i][j];

    for (int i = 0; i < index; i++) {
        std::cout << result[i] << " " << std::endl;
    }
}
Martin Cook
  • 419
  • 3
  • 15
0

Let assume that the actions are done consequently, i.e. first you already done this:

std::string result;
for (int i=0; i < 2; i++)
    for (int j=0; j < len; j++)
            result.push_back(Array[i][j]);

then you have already a char* array stored inside std::string.

char  *string = new char[result.size()];
string = strdup(test1.c_str());

Now if you skip the std::string step (why, platform doesn't support it?), you rather get something like that:

char  *string = new char[string_size];   // you have to either measure it beforehand or calculate from array size

int counter = 0;
for (int i=0; i < 2; i++)
    for (int j=0; j < len; j++)
            string[counter++] = Array[i][j];

If that's C code, replace new expression with malloc call. And this code got flaws like you either should allocate more memory than needed or you should count length of buffer before allocating it. Extreme case is to reallocate buffer when its capacity reached. std::string does that automatically.

I don't see why this can be a problem to devise, unless you're failing to tell us something important about what you need.

In general C++ code never looks like that unless you're designing your own containers. On ISO-compatible platform you'll have std::string, on most embedded systems, e.g. Arduino, you'll have access to String class.

Swift - Friday Pie
  • 8,633
  • 1
  • 16
  • 31