Fra*_*sco 2 c arrays string pointers
我在使用简单的复制功能时遇到了一些麻烦:
void string_copy(char *from, char *to) {
while ((*to++ = *from++) != '\0')
;
}
Run Code Online (Sandbox Code Playgroud)
它需要两个指向字符串作为参数的指针,它看起来不错但是当我尝试它时我有这个错误:
Segmentation fault: 11
Run Code Online (Sandbox Code Playgroud)
这是完整的代码:
#include <stdio.h>
void string_copy(char *from, char *to);
int main() {
char *from = "Hallo world!";
char *to;
string_copy(from,to);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你们
您的问题与您的副本的目的地有关:它是一个char*尚未初始化的.当您尝试将C字符串复制到其中时,您将获得未定义的行为.
您需要初始化指针
char *to = malloc(100);
Run Code Online (Sandbox Code Playgroud)
或者使它成为一个字符数组:
char to[100];
Run Code Online (Sandbox Code Playgroud)
如果您决定使用malloc,则需要free(to)在完成复制的字符串后调用.
您需要为 分配内存to。就像是:
char *to = malloc(strlen(from) + 1);
Run Code Online (Sandbox Code Playgroud)
free(to)当不再需要时,不要忘记通过调用释放分配的内存。