我正在閱讀 K&R C 編程語言書籍,并根據第 5 章練習 5 中的描述嘗試實作我自己的函式 strncpy 版本:
strncpy(s,t,n) 最多將 t 的 n 個字符復制到 s
我試圖寫以下內容:
#include <stdio.h>
void *strn_cpy(char *dest, const char *src, int n){
while ((*dest = *src ) && n--);
}
int main(){
char * s1 = "hello";
char * s2 = "abc";
strn_cpy(s1, s2, 2);
printf("%s", t1);
}
上面的代碼回傳一個 Segmentation fault 錯誤,我似乎無法弄清楚為什么,我理解函式的方式是,隨著回圈的每次迭代,*src 的當前值被復制到 *dest,之后兩個指標位置都增加按 1。然后,如果 *src 的值等于 '\0' 或者如果 n 等于 0,則回圈中斷。謝謝。
uj5u.com熱心網友回復:
char *s = "some string"創建一個指向無法更改的字串文字的指標。由于您嘗試寫入只讀字串,因此出現段錯誤。將其更改為char s[number]
#include <stdio.h>
void *strn_cpy(char *dest, const char *src, int n) {
while (n-- && (*dest = *src ));
}
int main() {
char s1[6] = "hello";
char *s2 = "abc";
strn_cpy(s1, s2, 2);
printf("%s", s1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367989.html
標籤:C
