C ++ strcpy复制字符串

时间:2016-11-24 09:18:02

标签: c++ string c-strings strcpy

这里有一个简短的代码,但它不会编译。知道出了什么问题吗?

char *str;
strcpy(str, "Hello world");
cout << str[6] << ' ' << &str[6] << endl;

1 个答案:

答案 0 :(得分:1)

您需要为字符串分配内存。你应该使用malloc,它为你的指针分配内存。

有关When to use malloc for char pointers

的更多信息

尝试:

char *str = malloc(sizeof(char) * 1024);  
相关问题