簡體   English   中英

一些代碼的說明

[英]Explanation of some code

我正在讀一本有關C ++的書(Bjarne Stroustrup撰寫的C ++導讀,第二版),其中有一個代碼示例:

int count_x(char* p,char x)
{
    if (p==nullptr) return 0;
    int count = 0;
    for(;*p!=0;++p)
        if (*p==x)
            ++count;
    return count;
}

在本書中,解釋了該函數的指針p必須指向char數組(即字符串?)。

所以我在main中嘗試了這段代碼:

string a = "Pouet";
string* p = &a;
int count = count_x(p, a);

但是count_x需要char而不是string,因此它不能編譯。 所以我嘗試了:

char a[5] {'P','o','u','e','t'};
char* p = &a;
int count = count_x(p, a);

但是,由於指針本身不能指向完整的數組,因此當然不會起作用。 因此,最后我嘗試制作一個指針數組:

 char a[5] {'P','o','u','e','t'};
 char* p[5] {&a[0],&a[1],&a[2],&a[3],&a[4]};
 int count = count_x(p, a);

但是該函數不接受數組,因為它不僅是一個char

因此,我不知道如何使用count_x函數(應該計算px的個數)。

您能給我一個使用此功能的工作代碼示例嗎?

示例函數count_x計算字符“ x”出現在char的“ a”數組中的次數。 因此,您必須將兩個參數傳遞給count_x函數:數組和字符:

char a[5] {'P','o','u','e','t'};
char* p = &a;
int count = count_x(p, a);  //This does not work because 'a' is not a character, but an array of characters.

//This is wrong because you are passing an array of pointers to chars, not an array of chars.
char a[5] {'P','o','u','e','t'};
char* p[5] {&a[0],&a[1],&a[2],&a[3],&a[4]};
int count = count_x(p, a);`

正確的方法是:

char a[5] {'P','o','u','e','t'};
char* p = a; //IT IS NOT &a, since 'a' can is already an array of chars. &a would be a pointer to array of chars
int count = count_x(p, 'o');  //Passing p, an array of chars, and one character to search

要么

char a[5] {'P','o','u','e','t'};
int count = count_x(a, 'o');  //Passing a, an array of chars, and one character to search

要么

char a[5] {'P','o','u','e','t'};
char c='u';
int count = count_x(a, c);  //Passing a, an array of chars, and one character to search

count_x函數對輸入char數組中給定字符的出現次數進行計數。

為了正確調用它,您需要向其提供一個char指針,該指針指向以null結尾的 char數組和一個字符。

在第一個示例中,您嘗試將string對象作為char指針傳遞,這是錯誤的,因為它們是兩種完全不相關的類型,盡管它們可能會在一天結束時包含字符。

string a = "Pouet";
string* p = &a;
int count = count_x(p, a); // Both arguments are wrong

您的第二次嘗試也失敗了:

char a[5] {'P', 'o', 'u', 'e', 't'}; // Lacks zero terminator
char* p = &a; // Invalid, address of array assigned to char pointer
int count = count_x(p, a); // Second argument is wrong, it wants a char

第三個也是:

char a[5] {'P', 'o', 'u', 'e', 't'}; // Ditto as above
char* p[5] {&a[0], &a[1], &a[2], &a[3], &a[4]}; // Array of char pointers
int count = count_x(p, a); // Both totally wrong

正確的方法是記住數組衰減,並通過指向第一個元素的指針傳遞以null終止的char數組:

char a[6] = "Pouet"; // Notice the '6' that accounts for '\0' terminator
char* p = a; // Array decays into a pointer
int count = count_x(p, 'o');

暫無
暫無

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

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