當把char* to ="You are a student."換成:char a[]="You are a student.";char *to=a;沒問題。編譯,連接沒問題,但運行就出問題了。調(diào)試顯示:"unhandled exception??in Test01025.exe:0xC000005:Access Violation."請問這是什么原因?#include<stdio.h>int main(){?void copy_string(char *from,char *to);?char *from="I am a teacher.";?char *to="You are a student.";//當把這一行換成:char a[]="You are a student.";char *to=a;沒有問題?printf("string a=%s\nstring b=%s\n",from,to);?printf("copy string a to string b:\n");?copy_string(from,to);?printf("\nstring a=%s\nstring b=%s\n",from,to);?return 0;}void copy_string(char *from,char *to){?while(*to=*from)?{to++;?from++;?}}
2 回答

qq_追夢_26
TA貢獻15條經(jīng)驗 獲得超2個贊
其實這個問題的本質(zhì)是在于const char* 和 char*的區(qū)別,前者是只能讀,不可以被修改的,后者可讀可寫:
你的例子當中a[]本身就可以讀可以寫的相當于char*,而當你換成char *to = “You are a student”的時候to就變成了const char *to了因此to所擁有的空間就不能被修改了 !
- 2 回答
- 0 關注
- 1606 瀏覽
添加回答
舉報
0/150
提交
取消