簡體   English   中英

C編程奇怪的輸出,我做錯了什么?

[英]C programming strange output, what did I do wrong?

#include<stdio.h>
#include<string.h>

int main()
{
 int j;
 char password[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
 j = strlen(password);
 printf("Size = %d\n", j);
 return 0;
}

輸出:大小 = 8

但是這段代碼

#include<stdio.h>
#include<string.h>

int main()
{
 int j;
 char password[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
 char enteredpassword[9];
 j = strlen(password);
 printf("Size = %d\n", j);
 return 0;
}

輸出:大小 = 14

這兩個代碼的區別在於未使用的“enteredpassword[9]”數組,是不是應該將password[8]的字符串長度從8更改為14?

strlen需要一個以空字符結尾的字符串。 您的字符數組缺少空終止符

char password[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0'};
//           ^^                                            ^^^^
j = strlen(password);

對非空終止的字符串調用strlen未定義行為,這意味着您的程序可能會崩潰或返回不可預測的結果。 請注意更改如何刪除password數組的硬編碼長度,讓編譯器計算出正確的大小。

您的password不是以空字符結尾的字符串。 如果您按慣例對其進行初始化:

char password[] = "abcdefgh";

或者

const char *password = "abcdefgh";

然后調用strlen會給你預期的答案。 (或者,如果您受約束並決心以艱難的方式去做,請使用

char password[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0'};

或者

char password[9] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0'};

.)

你的程序調用了未定義的行為,因此,可能的解釋是任何東西都可以作為輸出出現(如果幸運的話,你得到了段錯誤)。

char password[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};   //not a C-style string 

password不是以空字符結尾的字符串,將其傳遞給strlen將導致UB

j = strlen(password);   //will invoke UB

要么寫——

char password[9] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','\0'};

或者

char password[]="abcdefgh";

函數strlen()將與字符串一起使用。 C字符串是以\\0結尾的字符數組。 但是您的數組不是NULL \\0終止。

嘗試以下

char password[9] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0'};

您的代碼具有未定義的行為,因為您在未正確以 0 結尾的字符數組上調用strlen() ,即它們不是字符串。

在 C 中初始化字符串的正常方法是這樣的:

char mystr[100]="test string";

因為每個字符串都以一個 NULL 字符 ('\\0') 結束,所以你必須像下面這樣初始化你的字符串:

char password[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', '\\0'};

在這種情況下,您的密碼字符串以空字符結尾,並且 strlen() 將返回正確答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM