c++ - 一些代码的解释

标签 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 而不是 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 函数计算给定字符在输入 char 数组中出现的次数。

为了正确调用它,您需要向它提供一个指向 null-terminated char 数组和一个字符的 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');

关于c++ - 一些代码的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26627919/

相关文章:

c++ - 调用子方法

c++ - 使用 std::atomic::compare_exchange_strong 时,对 std::atomic 的写入是否会被其他线程看不到?

C++ - 无法从队列中删除元素

c++ - 如何在 char* 中存储整数和字符的串联?

c++ - 没有可用于结构 vector 的成员

c++ - 为什么我的 C++ 代码即使使用双重声明的变量也能编译?

c++ - 即使 CMenu 当前打开,如何强制 LVN_HOTTRACK 始终触发

c++ - 什么时候应该使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?

c++ - 运行快速修复引擎

c++ - 在构造函数中引用未初始化的对象