从char*复制到char arrray

Sij*_*ith -3 c visual-c++

我的角色指针指向一些记忆说"Hello world",我想将它与其他指针进行比较,后来想做strcpy.我认为可以做char*

char *A ="hello"
char *B ="";

strcmp(A,B); // this compares correctly because B points to diff string
strcpy(B,A); // will this statment copies the string alone or both will point to same memory
Run Code Online (Sandbox Code Playgroud)

MOH*_*MED 5

char *B ="";
Run Code Online (Sandbox Code Playgroud)

这意味着它B是一个指针,你已指向常量字符串"".

A字符串复制到Bwithstrcpy(B,A);

这意味着您正在将字符串复制AB指向的内存(并B指向常量字符串),因此这将导致未定义的行为

为了避免这样的问题,B指针应该指向一个内存空间,例如你可以将B指向一个用malloc分配的动态内存空间:

char *B = malloc(10*sizeof(char));
Run Code Online (Sandbox Code Playgroud)

并且您可以使内存大小与A字符串大小相同:

char *B = malloc((strlen(A)+1)*sizeof(char));
Run Code Online (Sandbox Code Playgroud)

+1表示字符串的空终止符

避免此问题的另一种解决方案:将B定义为字符数组而不是指针:

char B[10];
Run Code Online (Sandbox Code Playgroud)