#include <string.h>
#include <iostream.h>
int plus(int x,int y)
{
return x+y;
}
float plus(float x,float y)
{
return x+y;
}
double plus(double x,double y)
{
return x+y;
}
char *plus(char *x,char *y)
{
return strcat(x,y);
}
void main()
{
int i=12,j=34;
float x1=1.2,y1=4.5;
double x2=24.5,y2=635.4;
char *str1="object",char *str2="windows";
cout<<plus(i,j)<<endl;
cout<<plus(x1,y1)<<endl;
cout<<plus(x2,y2)<<endl;
cout<<plus(str1,str2)<<endl;
}
#include <iostream.h>
int plus(int x,int y)
{
return x+y;
}
float plus(float x,float y)
{
return x+y;
}
double plus(double x,double y)
{
return x+y;
}
char *plus(char *x,char *y)
{
return strcat(x,y);
}
void main()
{
int i=12,j=34;
float x1=1.2,y1=4.5;
double x2=24.5,y2=635.4;
char *str1="object",char *str2="windows";
cout<<plus(i,j)<<endl;
cout<<plus(x1,y1)<<endl;
cout<<plus(x2,y2)<<endl;
cout<<plus(str1,str2)<<endl;
}
{
return strcat(x,y);
}strcat会把指针y中的内容附加在指针x的后面,而x即str1,并没有分配多余的内存空间,这种操作是非法的!
{
return strcat(x,y);
}这个函数错了
返回局部变量的指针
{
return strcat(x,y);
}
这个肯定要改
就错了啊
应该为
char *str1="object",*str2="windows";
{
char *str1="object",char *str2="windows";
char sz[1024];
char * p = sz;
plus(str1,str2,p);
cout<<p<<endl;
}void plus(char *x,char *y,char * p)
{
p = strcat(x,y);
}
{
return strcat(x,y);
}函数本身没有错误,调用错误了,也可以说是没有了解strcat而写成这样的容易误用的函数,
char str1[32]; //32或者足够长
memset(str1,0,32);
strcpy(str1,"object");
cout<<plus(str1,str2)<<endl;
//or plus(str1,str2); cout<<str1<<endl; 另外plus定义成这样会好一点, char *plus(char *x,const char *y) ,尽量使用const是一种编程好习惯.如果不考虑效率问题,使用string比较好
string plus(const string & x,const string & y)
{
return x+y;
}char * str1 = "object";
char * str2 = "window";
cout<<plus(str1,str2)<<endl;
你的也不对.
你看strcat的定义,
char *strcat(
char *strDestination,
const char *strSource
);
The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of strSource overwrites the terminating null character of strDestination. The behavior of strcat is undefined if the source and destination strings overlap
这样才行吧:
void plus(const char *x,const char *y,char * p)
{
strcpy(p,x);
strcat(p,y);
}
#include <iostream.h>
int plus(int x,int y)
{
return x+y;
}
float plus(float x,float y)
{
return x+y;
}
double plus(double x,double y)
{
return x+y;
}
char *plus(char *x,char *y)
{
return strcat(x,y);
}
void main()
{
int i=12,j=34;
float x1=1.2,y1=4.5;
double x2=24.5,y2=635.4; char str1[1024];
memset(str1,0,1024);
strcpy(str1,"object");
char *str2="windows"; cout<<plus(i,j)<<endl;
cout<<plus(x1,y1)<<endl;
cout<<plus(x2,y2)<<endl;
cout<<plus(str1,str2)<<endl;
}
{
z=strcat(x,y);
return z;
}
在MAIN方法中,用:
char *str3=NULL;
cout<<plus(str1,str2,str3);
应该可以解决了
char *str1="object",char *str2="windows";
str1,str2 指向"object" "windows",都是字符串常量,不可被修改
而你的
strcat(str1,str2);
却把str2指向的字符串加到str1后,并存到str1,这里就会出错,str1不可被修改
知道错误你就好改了:
改法:
char str1[20]="object",char *str2="windows";
建议:尽量少用指针传递,很容易出错,而且要是动态分配还容易出现内存泄漏!