C ++返回char *问题 [英] C++ return char* problem
问题描述
你好!
我在函数中返回char *时遇到问题。
即时尝试构建一个获取字符串(少量单词)和单词编号的函数。
这个函数需要返回指定单词的指针。
例如:
char string [] = Hello World;
char * Pstring = string;
int num = 2 ;
char * word;
word = myfunction(Pstring,num);
cout<< word;
,结果将是
世界
现在好像我不能返回Pstring [i]而我不知道为什么..
我的算法找到了所需单词的索引,但我找不到一种方法将其位置作为指针返回。
希望很清楚,谢谢!
我尝试过:
这是我的功能
int i = 0 ,flag = 0 ;
// 搜索字位置;
for (; num> 0; i ++){
if (pstring [i]< = 122 && pstring [i]> = 65 ){
flag = 1 跨度>;
}
其他 if (flag&&(Pstring [i] == ' ' || Pstring [i] == ' ,' || Pstring [i] == ' 。')){
num--;
flag = 0 ;
}
}
return Pstring [i];
Pstring是一个指向char的指针 - 或者是一个字符串,如果你愿意的话。
Pstring [i]
是与说*(Pstring + i)
whingbis相同,这是字符串的单个元素:一个字符。
因为你的函数应该返回一个指向一个字符的指针,所以它不起作用!
有两种方法可以用你现有的代码返回:
return &(Pstring [i]);
或
返回 Pstring + i;
但我会dumpi
并使用PString作为指针而我增加了。
拼写错误[/ edit]
hello!
im having a problem returning char* in a function.
im trying to build a function that getting a string (with few words) and word number.
this function needs to return a pointer of the specified word.
for example:
char string[]="Hello World";
char* Pstring=string;
int num=2;
char* word;
word=myfunction(Pstring,num);
cout<<word;
and the results will be
World
now it seems that i cant return Pstring[i] and i dont know why..
my algorithm finds the index of the needed word but i just cant find a way to return his location as a pointer.
hope it was clear, thanks !
What I have tried:
this is my function
int i=0,flag=0;
// search for word location;
for(;num>0;i++){
if(pstring[i]<=122 && pstring[i]>=65){
flag=1;
}
else if(flag &&( Pstring[i]==' '||Pstring[i]==','|| Pstring[i]=='.')){
num--;
flag=0;
}
}
return Pstring[i];
Pstring is a pointer to a char - or a string, if you prefer.
Pstring[i]
is the same as saying*(Pstring + i)
whingbiswhich is a single element of the string: a character.
Since your function is supposed to return a pointer to a character, it doesn't work!
There are two ways to do the return with your existing code:
return &(Pstring[i]);
Or
return Pstring + i;
But I'd dumpi
and use PString as a pointer which I incremented instead.
[edit]typo[/edit]
这篇关于C ++返回char *问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!