字符串常量不能改写+段错误(ubuntu)

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


void copy_string(char *a, char* b);
int main()
{
char *a = "i am a teacher!\n";
char *b = "you are a student!\n";

char c[20] = "i am a teacher!\n";

        char d[20] ="you are a student!\n";

   

 //-----------------------------------------

printf("copy c to d\n");
copy_string(c, d);
printf("d: %s\n", d);

//---------------------------------------------  下面这是错误的,因为字符串常量不可改写!

 //     printf("copy a to b\n");
// copy_string(a, b);
// printf("d: %s\n", b);

//---------------------------------------------

return 0;

}
void copy_string(char *a, char *b)
{
for (; *a!='\0'; a++, b++)
{
*b = *a;
}
*b = '\0';

}

上面的错误在 ubuntu中为   “段错误!”-----------------

错误原因类似于:

char *a = "helloworld!";

a[5] = 'k';   //------------------------------------错!  


无论是在windows还是在ubuntu中,,声明的字符串常量,都是只能读,不能写的,理解字符串常量。这应该跟编译器有关.

要改正这个错误可以将声明定义的时候 char*   改为  定义成数组



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值