指針和數組
- 指針數組是一個數組,數組的每個元素都是指針。它適用于需要存儲多個指針的場景,如字符串數組。
- 數組指針是一個指針,指向一個數組。它適用于需要傳遞整個數組給函數或處理多維數組的場景。
?
函數指針:函數指針的定義需要指定函數的返回類型、參數列表以及指針的名稱。
//return_type (*pointer_name)(argument_type1, argument_type2, ...);
- return_type:函數返回值的類型。
- pointer_name:函數指針的名稱。
- argument_type1, argument_type2, ...:函數參數的類型列表
?
?
?sizeof和指針與數組
Strlen和字符數組:
- strlen函數:用于計算字符串的長度,不包括終止符\0。
- 字符數組:用于存儲字符串,必須以\0結尾。
?
庫函數模擬實現手撕Memcopy:
void* my_memcpy(void* dest, const void* src, size_t n) {if (dest == nullptr || src == nullptr) {return nullptr;}char* d = static_cast<char*>(dest);const char* s = static_cast<const char*>(src);// 內存重疊檢查if (d > s && d < s + n) {// 從后向前拷貝for (size_t i = n; i != 0; --i) {d[i - 1] = s[i - 1];}}else {// 正常從前向后拷貝for (size_t i = 0; i < n; ++i) {d[i] = s[i];}}return dest;
}
?實現Mommove:
void* my_memmove(void* destination, const void* source, size_t num) {// 如果源和目標指針相同,則無需移動if (destination == source) {return destination;}// 將void指針轉換為char指針,以便逐字節操作char* dest = static_cast<char*>(destination);const char* src = static_cast<const char*>(source);// 如果源區域在目標區域之前或重疊,則從后向前復制if (src < dest && src + num > dest) {// 從后向前復制for (size_t i = num; i != 0; --i) {dest[i - 1] = src[i - 1];}}else {// 從前向后復制for (size_t i = 0; i < num; ++i) {dest[i] = src[i];}}return destination;
}
實現strstr?
char* my_strstr(const char* haystack, const char* needle) {// 如果needle是空字符串,根據標準定義,返回haystackif (*needle == '\0') {return const_cast<char*>(haystack);}// 獲取主串和子串的長度size_t haystack_len = strlen(haystack);size_t needle_len = strlen(needle);// 如果子串長度大于主串長度,肯定找不到if (needle_len > haystack_len) {return nullptr;}// 遍歷主串,尋找子串的起始位置for (size_t i = 0; i <= haystack_len - needle_len; ++i) {// 比較子串和主串的對應部分size_t j = 0;while (j < needle_len && haystack[i + j] == needle[j]) {++j;}// 如果整個子串都匹配,返回匹配的起始位置if (j == needle_len) {return const_cast<char*>(haystack + i);}}// 如果沒有找到子串,返回nullptrreturn nullptr;
}
自定義類型:內存對齊:
?
大小端的判斷:
bool isLittleEndian() {union {uint32_t i;unsigned char c[4];} u;u.i = 0x01020304;// 檢查最低地址的字節是否為最低有效字節return (u.c[0] == 0x04);
}int main() {if (isLittleEndian()) {cout << "系統是小端字節序。" << endl;}else {cout << "系統是大端字節序。" << endl;}return 0;
}
解釋:
u.i
被賦值為0x01020304
。- 如果系統是小端,
u.c[0]
將是0x04
;如果是大端,u.c[0]
將是0x01
。 - 根據
u.c[0]
的值判斷字節序。?
這次是對C中我還不清楚并且比較重要的知識進行總結,順序可能會有點亂,還請見諒
?
?