[英]Getting different lengths for the same operation with different number values in C
我有2個for循環,其中使用來自字母表的字母填充數組。 我有一個lowercase
數組集和一個uppercase
數組集。 問題是當我用字母初始化數組時,長度返回的不同。
char uppercase[26];
char lowercase[26];
int indexUpper = 0;
int indexLower = 0;
// Get uppercase array:
for(int a = 65; a <= 90; a++){
uppercase[indexUpper] = a;
indexUpper++;
}
// Get lowercase array:
for(int b = 97; b <= 122; b++){
lowercase[indexLower] = b;
indexLower++;
}
printf("UPPERCASE = %lu\n", strlen(uppercase));
printf("LOWERCASE = %lu\n", strlen(lowercase));
$=> UPPERCASE = 26
$=> LOWERCASE = 27
如果這是沒有道理的,我深表歉意。 我確實在嘗試學習和理解C語言及其規則。 感謝所有貢獻者。
strlen()
讀取字符數組,直到找到一個NUL字節( '\\0'
,數值為零)為止。 您的數組不包含任何數組,因為您尚未在其中分配一個數組。
這意味着strlen
將繼續讀取超過數組末尾的值 ,這是非法的,並且未定義結果行為。 獲得27相當溫和,您可能會獲得任意數字,否則您的程序可能會崩潰。
如果要使用strlen()
,則應在字符串末尾顯式分配一個NUL字節,當然還要為其分配空間。
也許是這樣的:
#include <stdio.h>
#include <string.h>
int main(void)
{
char upper[27];
int i;
for (i = 0 ; i < 26; i++) {
/* This only works in a character set where the letters
are contiguous */
upper[i] = 'A' + i;
}
/* i == 26 now */
upper[i] = '\0';
printf("len: %u\n", (unsigned) strlen(upper));
return 0;
}
(盡管在這里使用strlen
似乎毫無意義,因為您已經知道這些數組中的項目數。)
使用strlen
,char數組必須以nul終止-但是您的數組不是,因此您有未定義的行為。
要打印數組的大小,請嘗試:
printf("UPPERCASE = %zu\n", sizeof uppercase);
printf("LOWERCASE = %zu\n", sizeof lowercase);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.