strcpy抛出内存异常

Vik*_*rni 2 c++

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

using namespace std;

int main()
{
    const char *a="hello";
    char *b;
    strcpy(b,a);
     cout<<b;


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这段代码存储内存异常.为什么?

Ton*_*roy 7

char* b是一个尚未指向任何内存的指针......它只是一个随机地址.您尝试复制该a地址内存的内容.相反,首先指向b一些内存 - 本地数组或来自new char[].

char buffer[128];
char* b = buffer;

char* b = new char[128];
// use b for a while...
delete[] b; // release memory when you've finished with it...
          // don't read/write data through b afterwards!
Run Code Online (Sandbox Code Playgroud)

(或直接将其直接复制到buffer:-))

BTW,C++有一个<string>更容易使用的标题:

#include <string>

int main()
{
    std::string s = "hello";
    std::string t = s;
    std::cout << t << '\n';   // '\n' is a "newline"
}
Run Code Online (Sandbox Code Playgroud)

如果您正在编写新代码,请选择std :: string,但迟早您也需要了解所有这些char*内容,尤其是当C++代码需要与C库交互时.