使用指针在C中复制字符串 [英] Copy string in C, using pointer
问题描述
我是初学者程序员.我编写了以下代码,使用指针将一个字符串复制到另一个字符串中. 但是我没有得到输出.编译器说分段错误. 我已经遍历该程序,但无济于事.我无法找到故障以及如何解决. 很难相信,但是我已经被困了将近2个小时了. 任何帮助将不胜感激.
I am a beginner programmer. I wrote the following code to copy the one string into other, using pointers. But I am not getting the output. The compiler says segmentation fault. I have gone over and over the program, but to no avail. I am not able to locate the fault, and how to fix it. It would be hard to believe but I have been stuck for almost 2 hours now. Any help is greatly appreciated.
#include<stdio.h>
char *copy(char*, char*);
int main() {
char *str1 = "avanti";
char *str2 = "ujj";
printf("%s\n", str1);
char *result = copy(str1, str2);
printf("%s", result);
}
char *copy(char *str1, char *str2){
int i=0;
while (*(str2+i) != '\0') {
*(str1+i) = *(str2+i);
i++;
}
*(str1+i) = '\0';
return str1;
}
推荐答案
"avanti"
是字符串常量,不是可以复制到的位置.您可以将其更改为char str1[] = "avanti";
.这是一个由字符串常量"avanti"
"avanti"
is a string constant, not a place you can copy to. You might change it to char str1[] = "avanti";
This is an array of characters that is initialized with the value of the string constant "avanti"
这篇关于使用指针在C中复制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!