一些代码的解释

时间:2014-10-29 10:26:41

标签: c++

我正在读一本关于C ++的书(C ++之旅,Bjarne Stroustrup,第二版),还有一个代码示例:

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不是字符串所以它不编译。 所以我试过了:

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函数(应该计算xp的数量。

您能否举例说明使用此功能的工作代码?

2 个答案:

答案 0 :(得分:1)

样本函数count_x计算字符“x”出现在“a”数组char中的次数。因此,您必须向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

答案 1 :(得分:1)

count_x函数计算输入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

这样做的正确方法是记住array decaying并通过指向第一个元素的指针传递一个以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');