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’
2
  • If you'll use char arrays, why don't you just say char string1[] = "hello world";? Commented Jul 28, 2013 at 17:34
  • 1
    refer this. stackoverflow.com/questions/347949/… Commented Jul 28, 2013 at 17:38

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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;
}

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.