1

below is my code

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

int main()
{
    std::string data;

    data = "hello world";

    char string[] = new char [data.length()+1];;
strcpy(string, data.c_str());


}

I got an error..

file.cpp: In function ‘int main()’:
file.cpp:14:46: error: initializer fails to determine size of ‘string’

What should i do as I want copy the content of string data into char string[]

Thanks for helping.

2
  • 1
    It's not the problem this time, but avoid using (even namespaced) standard type names as variable names. I for one always have to do a double take. Commented Jul 28, 2013 at 16:31
  • Once you got the string declared correctly, you should probably use memcpy() as the length of the string is known unless the string to be copy may contain null characters. Commented Jul 28, 2013 at 16:41

5 Answers 5

6

Change to the following:

char* string = new char[data.size()+1];
Sign up to request clarification or add additional context in comments.

Comments

2

Use char *string, not char string[].

The char string[] means that you define an array, and size of the array should be evaluated from the initializer in compile-time.

Comments

1

In order to get it to compile, you'd have to use a char* instead of a char[]. char[] in this case requires a constant size, and since data is not a compile-time constant, the size cannot be determined.

Comments

0

Try something like this :

string Name="Hello FILE!"
int TempNumOne=Name.size();
char Filename[100];
for (int a=0;a<=TempNumOne;a++)
    {
        Filename[a]=Name[a];
    }

Comments

0

You should do :

char* string = new char[data.length()+1];
//  ^

strcpy take two pointers as argument. char string[] means you are declaring an array.

Here is the prototype of the function :

char *strcpy(char *dest, const char *src);

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.