从C++中的函数返回字符的地址

Returning an address of a character from a function in C++

本文关键字:字符 地址 返回 函数 C++      更新时间:2023-10-16

我正在尝试编写一个程序,该程序将一个字符串作为输入,并在该字符串中查找一个字符。然后,函数应该返回该特定字符的地址。据我所知,逻辑似乎是正确的,但出于某种原因,当我调用函数时,它会返回目标字符后面的字符串的其余部分,而不是字符的地址。例如:如果我输入"Hello"并输入"E"作为目标,函数将返回"llo"。如有任何帮助/解释,我们将不胜感激。

#include<iostream>
#include<cstdlib>
#include<cstring>
char *mystrrchr (char *s, char c)
{
    char *charptr;
    for(int i = 0;i<strlen(s)-1;i++)
    {
        if(s[i] == c)
        {
            charptr = &s[i];
        }
    }
    return charptr;
    }
using namespace std;
void main()
{
    char *string = new char[100];
    char a;
    cout<<"Enter string : ";
    cin.getline(string,100);
    cout<<"Enter character to find in string : ";
    cin>>a;
    cout<<"The adress of the last occurence of the character entered is : "<<mystrrchr(string,a)<<endl;
}

您正在打印char*。默认行为是将其打印为以C样式null结尾的字符串,而不是地址。尝试:

... << static_cast<const void*>(mystrrchr(string,a))

例如:如果我输入"Hello"并输入"E"作为目标,函数将返回"llo"

没有。您希望函数返回特定字符的地址,而这正是它的作用。

问题出在你的输出上。C样式字符串由指向其第一个字符的指针表示,并以null字符结束。std::cout将函数的结果解释为C样式字符串,并一直输出到最后。

如果要输出地址,则应将结果强制转换为void *

static_cast<void*>(ptr);

附带说明一下,您不应该在循环中使用strlen,因为它将在每次迭代中迭代整个字符串。对于像"hello"这样的字符串,这可能不是问题,但对于较长的字符串,它很快就会成为问题。

相反,在循环外使用strlen,如下所示:

int len = strlen(str);
for (int i = 0; i < len; ++i) { ... }

程序打印字符串而不是地址的原因是ostream重载了"char*",因此有必要将其强制转换为"void*"。

这似乎对我有用——您的函数返回一个正确字符的指针。

不过,有几件事需要澄清才能使其正常工作:

我在void中添加了一个静态铸造*:

static_cast<void*>(found)) 

输出(所以它输出地址),然后我在下一行输出子串。

这是因为cout在传递指向字符(char*)的指针时需要c_string,所以当您传递mystrrchr的返回时,它会打印字符串
为了让它打印地址,我们需要将它强制转换为另一种类型的指针(对于所有其他指针,行为是打印地址)。

我还修复了:main现在返回int,因为void main(){}在C++中无效:

prog.cpp:19:11: error: ‘::main’ must return ‘int’  

mystrrchr更改为只计算字符串的长度一次
更改了mystrrch中的for循环,因此不需要计算字符串的长度,而是在尚未达到字符串的null终止符时循环。

请在此处查看:http://ideone.com/TmTwFM
输入:

hello
e

输出:

The address of the last occurence of the character entered is : 0x96fd009
The string from the last occurence of the character entered is : ello

更新代码:

#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
char *mystrrchr (char *s, char c)
{
    char *charptr;
    for(int i = 0; s[i]; i++)
    {
        if(s[i] == c){
            charptr = &s[i];}
    }
    return charptr;
}
int main()
{
    char *string = new char[100];
    char a;
    cout<<"Enter string : ";
    cin.getline(string,100);
    cout<<"nEnter character to find in string : ";
    cin>>a;
    char* found = mystrrchr(string,a);
    cout<<"nThe address of the last occurence of the character entered is : "<<static_cast<void*>(found)<<
          "nThe string from the last occurence of the character entered is : "<<found<<endl;
}