试图创建一个简单的函数,在字符串中查找单个字符"就像strchr()会",我做了以下内容:
char* findchar(char* str, char c)
{
char* position = NULL;
int i = 0;
for(i = 0; str[i]!='\0';i++)
{
if(str[i] == c)
{
position = &str[i];
break;
}
}
return position;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止它的作用.但是,当我看到strchr()的原型时:
char *strchr(const char *str, int c);
Run Code Online (Sandbox Code Playgroud)
第二个参数是int?我很想知道..为什么不是炭?这是否意味着我们可以像使用char一样使用int来存储字符?
这让我想到第二个问题,我试图改变我的函数接受一个int作为第二个参数......但我不确定这样做是否正确和安全:
char* findchar(char* str, int c)
{
char* position = NULL;
int i = 0;
for(i = 0; str[i]!='\0';i++)
{
if(str[i] == c) //Specifically, is this line correct? Can we test an int against a char?
{
position = …Run Code Online (Sandbox Code Playgroud) c ×1