其實時間長了,稍微研究后,再來品味,別有一番滋味
總是看著混亂,但是靜下來看,還是能琢磨透的,只是看著復雜,本質是兩套風格,然后又要有交集,所以就看起來復雜
// 首先字符串 在c++ 風格叫字符串,在c風格 叫字符數組//sizeof 獲取對象大小、數據類型大小//strlen 用于獲取以空字符 \0 結尾的字符串的長度 #include <cstring>(C)或 #include <string>(C++)// size 僅適用于C++標準庫的容器類,用于獲取容器中元素的數量//length 僅適用于C++標準庫的字符串類(如 std::string),用于獲取字符串的長度。
// 其中length 和size的區別 前者是使用string 字符串 后者適用于所有C++標準庫的容器類,包括 std::vector、std::list、std::set int main()
{char source[] = "Hello";char destination[2];char tem[128] = {0};char tem2[128] = {0};char tem3[128] = {0};strncpy(destination, source, 3);for(int i = 0; i < sizeof(destination); ++i){std::cout<<destination[i]<<" "<<std::endl;}strcpy(tem, destination);strncpy(tem2, destination, sizeof(destination));strncpy(tem3, destination, strlen(destination));//destination[5] = '\0';printf("\n");std::cout << "Destination: " << destination <<"\ntem: "<< tem<<"\ntem2:"<<tem2<<"\ntem3:"<<tem3<<std::endl;return 0;
}/*
輸出
H
e Destination: Helello
tem: Helello
tem2:He
tem3:Helello
*//*
解答:Destination對象分配的內存為2 所以字符數組只有兩個字符 H etem 是完整的 destination數組 因為字符數組空間不夠用,所以沒有在字符數組里面截斷,所以長度還是最開始的長度tem2 是截取 destination的兩個元素tem3 截取的是destination 到 \0 的元素 也就是完整的字符串內容
*/