从C++中的函数返回字符的地址
Returning an address of a character from a function in C++
我正在尝试编写一个程序,该程序将一个字符串作为输入,并在该字符串中查找一个字符。然后,函数应该返回该特定字符的地址。据我所知,逻辑似乎是正确的,但出于某种原因,当我调用函数时,它会返回目标字符后面的字符串的其余部分,而不是字符的地址。例如:如果我输入"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;
}
- 如何获取C++字符数据类型的地址
- 打印字符数组地址的正确方法
- 为什么我无法获取 MSVS2019 / C++ 中字符或uint8_t变量的内存地址?
- 使用 C++将 IP 地址附加到字符*
- C++指针分配字符数组的地址
- 为什么 C++ 中的字符数组返回其项目而不是地址?
- 字符数组地址和整数数组地址
- 在带有 (void*) 强制转换的字符串中打印字符的内存地址
- 为什么这段代码给出错误......'a'是指针到字符指针,应该存储's'的地址,因为s是指向数组的第一个元素的指针
- 如何在 2D 字符数组中打印 [x][y] 元素的地址?(C++)
- 读取字符 * 始终具有相同的地址
- C++ 在 64 位平台中传递字符数组地址
- 获取字符数组地址,然后转换为指针字符
- 如何反转字符指针数组的地址
- 如何使用字符指针查找字符串的地址
- 指向字符地址的指针的值
- 将文件的常量字符* 地址传递给 ifstream 对象的问题
- 为什么十六进制地址是14个字符
- c++seekg似乎返回了一个十六进制地址,而不是.txt文件中的实际字符
- &运算符不生成字符地址