記住char
陣列SPECI al,這意味着他們有大小,您在聲明它們時指定,長度,這取決於它們的內容。數組的大小是分配給它的內存量。字符串的長度是終止空字符之前的字符數('\0'
)。
some_func() {
int len = 20; // Size of the array
char chaine[len]; // Uninitialized array of size 20.
memset(chaine, '\0', sizeof(chaine)); // Init to all null chars, len = 0
strcpy(chaine, "WORDS"); // Copy a string, len = 5
char *chaine2 = function(chaine, sizeof(chaine));
printf("%s\n", chaine2);
free (chaine2);
}
當你將一個數組傳遞給一個函數時,它就像一個指針一樣對待。所以sizeof(str)
裏面的函數會一直返回指向char的指針的大小,而不是原始數組的大小。如果你想知道的字符串是多久,確保它是空值終止,並使用strlen()
這樣的:
char *function(char *str, int len) {
// Assume str = "WORDS", len = 20.
char *new_str = malloc(len); // Create a new string, size = 20
memset(new_str, '\0', len); // Initialize to nulls
memset(new_str, '*', strlen(str)); // Copy 5 '*' chars, len = 5
return new_str; // Pointer to 20 bytes of memory: 5 '*' and 15 '\0'
}
你沒有初始化'chaine'你未能表現出代碼在'功能'。 – 2012-04-26 02:20:34