/*** str_copy.c ***/ #include<stdio.h> void copy_str21(char *from, char *to) { for(; *from != '\0'; from++,to++) { *to = *from; } *to = '\0'; return; } int main() { char *from = "abcd"; char buf2[100]; copy_str21(from,buf2); printf("buf2:%s\n",buf2); return 0; }
程序內存四區分析:ubuntu
char *from = "abcd"; 操做系統在在常量區分配一個內存存放」abcd」,在棧區定義分配一塊內存,取名位from,from指向的這塊內存存儲「abcd」的首地址。數組
char buf2[100]; 操做系統在棧區分配一塊內存,開頭與棧區增加方向相反,大小爲100個字節函數
copy_str21(from,buf2); 程序進入到該函數中spa
void copy_str21(char *from, char *to) 操做系統在繼續在棧中分配兩塊內存,分別用to和from指向這兩塊內存。而且把mian函數中的from,to地址首部存放在該函數中分配到from,to指針指向的內存操作系統
for(; *from != '\0'; from++,to++)指針
{code
*to = *from;blog
}內存
copy_str21函數中from指針存儲的地址是常量「abcd」的首地址,to指針存儲的是mian函數中buf2數組的首地址。而後把from指針不斷後移區內容賦值給to指針不斷後移所指向的內存空間。字符串
*to = '\0'; 因爲buf2沒有進行初始化,因此最後要在結束的時候把最後面的內存賦值0,做爲C語言字符串的結尾。
而後程序返回,copy_str21棧地址回收,主函數打印buf2字符數組。
copy函數技術演練
/*** str_copy.c ***/ #include<stdio.h> void copy_str21(char *from, char *to) { for(; *from != '\0'; from++,to++) { *to = *from; } *to = '\0'; return; } void copy_str22(char *from,char *to) { for(;*from != '\0';) { *to++ = *from++; } *to = '\0'; return ; } void copy_str23(char *from,char *to) { while( (*to = *from) != '\0') { from++; to++; } } void copy_str24(char *from,char *to) { while((*to++ = *from++) != '\0') { ; } } void copy_str25(char *from,char *to) { while( (*to++ = *from++) ); } int main() { char *from = "abcd"; char buf1[100]; char buf2[100]; char buf3[100]; char buf4[100]; char buf5[100]; copy_str21(from,buf1); printf("buf1:%s\n",buf1); copy_str22(from,buf2); printf("buf2:%s\n",buf2); copy_str23(from,buf3); printf("buf3:%s\n",buf3); copy_str24(from,buf4); printf("buf4:%s\n",buf4); copy_str25(from,buf5); printf("buf5:%s\n",buf5); return 0; }
運行結果:
exbot@ubuntu:~/shareWin/CAndC++/20190924$ gcc strcopy.c -o strcopy -g
exbot@ubuntu:~/shareWin/CAndC++/20190924$ ./strcopy
buf1:abcd
buf2:abcd
buf3:abcd
buf4:abcd
buf5:abcd
/*** copy_str.c ***/ #include<stdio.h> int copy_str26_good(char *from,char *to) { if(from == NULL || to == NULL) { return -1; } while(*to++ = *from++); return ; } int copy_str27_verygood(char *from,char *to) { if(from == NULL || to == NULL) { return -1; } char *tempfrom = from; char *tempto = to; while(*tempto++ = *tempfrom++); return ; } int main() { int ret = 0; char *from = "abcd"; char buf[100]; char buf1[100]; //傳進來的指針若是被初始化指向null的話,是不須要被修改的 //由於null和0是操做系統內部一塊沒法訪問和修改的地址空間存儲的 //因此提早對傳進來的指針進行判斷,若是爲null,則返回錯誤 ret = copy_str26_good(from,buf); if(-1 == ret) { printf("ponit p or buf is null\n"); } else { printf("copy success buf = %s\n",buf); } //不要輕易改變形參的值,要引入一個輔助的變量指針,把形參接過來 ret = copy_str27_verygood(from,buf1); if(-1 == ret) { printf("ponit p or buf is null\n"); } else { printf("copy success buf1 = %s\n",buf1); } return 0; }
運行結果:
exbot@ubuntu:~/shareWin/CAndC++/20190924$ ./copy_str
copy success buf = abcd
copy success buf1 = abcd