0
#include <stdio.h>
#include <string.h>

int main()
{

    std::string data;
    data = "hello world";
    char string1[] = data;

}

If I must use char string1[] and not char *string1, is there a way I can copy content of string data into this char string1[]?

file.cpp: In function ‘int main()’:
file.cpp:13:22: error: initializer fails to determine size of ‘string1’
Mat
  • 202,337
  • 40
  • 393
  • 406
user1777711
  • 1,604
  • 6
  • 22
  • 32

4 Answers4

1

You can call method c_str on std::string object and copy result to your array.

Michał Banasiak
  • 950
  • 6
  • 13
0

Since the size of data may be variable, it cannot be copied via initialization of a static array.

One way you can do it is with dynamic allocation (which C++ string handles automatically):

char *string1 = strdup(data.c_str());
// do stuff with string1
free(string1);
tohava
  • 5,344
  • 1
  • 25
  • 47
0

Using stack memory (only if you are sure that the data.size() is less than 1000.):

char result[1000];
strcpy(result, data.c_str());

Or using heap memory:

char* result = new char[data.size() + 1];
strcpy(result, data.c_str());
// ...
delete[] result;
sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
0

If you are familiar with loops, then the easiest way is to copy the contents of string to char array one by one. As you are not going to use char pointer so you have to fix the size of char array, say 20.

int main()
{
    string data;
    data = "hello world";
    int size = data.size(); // size of data
    char string1[20]; //you can change the size of char array but it must be greater than size of data string
    for (int i = 0; i < size; i++) {
        string1[i] = data[i];
    }
    return 0;
}
nommyravian
  • 1,316
  • 2
  • 12
  • 30