[英]How to print the contents of a character array in the main function whose base address is returned by a function through a character pointer?
我试图通过在另一个函数返回的字符指针中接受该数组的基地址来打印主函数中的字符数组的内容。 实际上,这里的代码是接受带有元音的字符串,并返回不带元音的修改后的字符串。 但是当我在main函数中打印字符数组时,代码不打印任何内容。 可以使用字符串类来做,但是我想知道使用字符指针时出现了什么问题。
#include<iostream>
#include<string.h>
using namespace std;
char * print(char * s)
{
int j=0,len;
while(s[j]!='\0')
j++;
len=j;
char scopy[len];
char * sn;
j=0;
for(int i=0;i<len;i++)
{
if(s[i]!='a' && s[i]!='e' && s[i]!='i' && s[i]!='o' && s[i]!='u' && s[i]!='A' && s[i]!='E' && s[i]!='I' && s[i]!='O' && s[i]!='U')
{
scopy[j]=s[i];
j++;
}
}
sn=scopy;
return sn;
}
int main()
{
int n;
cout<<"enter n:\n";
cin>>n;
char st[n];
cout<<"enter string:\n";
cin>>st;
char * ps=print(st);
cout<<"the string is\n"<<ps[0]<<ps[1]<<ps[2]<<"\n"; //Here when i print the array contents individually using the base pointer, it prints successfully
for(int i=0;ps[i]!=NULL;i++) //the problem is here, it does not print anything
cout<<ps[i];
}
您的代码将调用Undefined Behavior ,因为它返回一个指向局部变量的指针,该局部变量将在函数终止后立即超出范围:
char * print(char * s)
{
...
char scopy[len];
char * sn;
...
sn=scopy;
return sn;
}
此外,您不对字符串进行空终止,然后执行以下操作:
for(int i=0; ps[i]!=NULL ;i++)
cout << ps[i];
ps
不是以null结尾的,因此ps[i] != NULL
将始终为true。
由于您使用的是C ++,因此我强烈建议您使用std::string
,而不要使用C风格的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.