非常經典的 C 語言面試題 ?
strcpy 和 memcpy 雖然都是“拷貝數(shù)據(jù)”的函數(shù),但它們的用途、拷貝單位、終止條件、適用場景完全不同。下面是詳細對比。
?? 一、函數(shù)原型與定義
// 頭文件:<string.h>
char *strcpy(char *dest, const char *src);
void *memcpy(void *dest, const void *src, size_t n);
?? 二、核心區(qū)別對比表
| 對比項 | strcpy |
memcpy |
|---|---|---|
| 功能 | 拷貝字符串 | 拷貝任意內存塊 |
| 終止條件 | 遇到 \0 結束 |
拷貝指定字節(jié)數(shù) n |
| 參數(shù)類型 | char* |
void*(可用于任意類型) |
| 返回值 | 返回目標字符串首地址 | 返回目標內存首地址 |
是否拷貝 \0 |
會拷貝源字符串的 \0 |
不會自動拷貝 \0,除非計入 n |
| 安全性風險 | 可能越界(若源字符串未以 \0 結尾) |
需確保目標和源不重疊 |
| 適用場景 | 字符串操作 | 內存數(shù)據(jù)、結構體、數(shù)組、緩沖區(qū) |
| 效率 | 較低(逐字節(jié)檢測 \0) |
較高(按字節(jié)或字塊直接復制) |
?? 三、舉例說明
? strcpy 示例(拷貝字符串)
#include <string.h>
#include <stdio.h>
int main() {
char src[] = "hello";
char dest[10];
strcpy(dest, src); // 自動拷貝包括 '\0'
printf("%s\n", dest); // 輸出: hello
return 0;
}
?? 若
src沒有\0結尾,strcpy會一直讀到非法內存區(qū),造成 越界或段錯誤。
? memcpy 示例(拷貝任意數(shù)據(jù))
#include <string.h>
#include <stdio.h>
int main() {
int a[3] = {1, 2, 3};
int b[3];
memcpy(b, a, sizeof(a)); // 拷貝 12 字節(jié)(3個int)
printf("%d %d %d\n", b[0], b[1], b[2]);
return 0;
}
memcpy只是單純復制二進制內容,不關心數(shù)據(jù)類型或終止符。
?? 四、常見錯誤與陷阱
? 錯誤示例 1:把 memcpy 當 strcpy
char src[] = "hello";
char dest[10];
memcpy(dest, src, strlen(src)); // ? 忘記拷貝 '\0'
printf("%s", dest); // 輸出亂碼或崩潰
? 正確做法:
memcpy(dest, src, strlen(src) + 1); // +1 復制 '\0'
? 錯誤示例 2:目標和源內存重疊
char str[] = "abcdef";
memcpy(str + 2, str, 4); // ? 源和目標區(qū)域重疊,結果未定義
? 正確做法:
memmove(str + 2, str, 4); // 使用 memmove 處理重疊
?? 五、內存層級差異
| 函數(shù) | 操作粒度 | 檢測終止符 | 可處理數(shù)據(jù)類型 |
|---|---|---|---|
strcpy |
字符級 | 是 (\0) |
僅字符字符串 |
memcpy |
字節(jié)級 | 否 | 任意數(shù)據(jù)類型 |
? 六、面試回答總結模板
strcpyis used to copy a null-terminated string, and it stops when it meets'\0'.
It can only handle string data.
memcpycopies a fixed number of bytes, regardless of content, and can be used for any type of memory such as arrays or structures.
It’s faster but must ensure memory regions do not overlap.In short,
strcpydepends on'\0', whilememcpydepends onn.
?? 七、記憶口訣
??
strcpy→ “string copy” → 以\0結尾
??memcpy→ “memory copy” → 按字節(jié)長度
并且:指針自加(如 p++)時,移動的字節(jié)數(shù)取決于指針所指向的數(shù)據(jù)類型,而不是固定的 4 個字節(jié)
同時對指針操作時要確保其已經初始化,否則為野指針,出現(xiàn)未定義行為。
浙公網(wǎng)安備 33010602011771號