繁体   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