主题:返回字符串的初级问题?
xf_z
[专家分:0] 发布于 2010-04-21 11:04:00
我想做一个返回字符串的函数,可是下面的代码一执行程序就死了
char* sjs2()
{
int a;
char* s[16]={"48","49","50","51","52","53","54","55","56","57","65","66","67","68","69","70"};
char* str[100];
for (int i=0; i<8; i++ )
{
srand(time( NULL));
a=rand()%17;
strcat(str[100],str[i]);
}
return str[100];
}
回复列表 (共4个回复)
沙发
耶路撒冷 [专家分:650] 发布于 2010-04-21 13:14:00
strcat(str[100],str[i]) 你的两个参数的问题
板凳
耶路撒冷 [专家分:650] 发布于 2010-04-21 13:17:00
char* s[16]={"48","49","50","51","52","53","54","55","56","57","65","66","67","68","69","70"};
char* str[100];
你把这两个声明为指针类型显然不是你想的,你的初始化又是字符串类型,声明为char就得了,不是char*,你的初始化再做相应的修改
3 楼
liuf403 [专家分:120] 发布于 2010-04-21 13:48:00
我理解你的意思应该写成这样:(但整个代码我没看出来你想表达什么)
char* sjs2()
{
int a;
char* s[16]={"48","49","50","51","52","53","54","55","56","57","65","66","67","68","69","70"};
char str[100] = {0};
for (int i=0; i<8; i++ )
{
srand(time( NULL));
a=rand()%17;
strcat(str,str[i]);
}
str[strlen(str) - 1] = '\0'
return;
}
最后的return不能返回字符串,因为你是局部定义的数组,返回的时候系统会释放掉的,如果你真要这样做的话,就应该设置个函数参数,从那里把数组传进来,不然这样写就会有问题.
4 楼
liuf403 [专家分:120] 发布于 2010-04-21 13:53:00
这样写可以.
char* sjs2(char str[])
{
int a;
char* s[16]={"48","49","50","51","52","53","54","55","56","57","65","66","67","68","69","70"};
for (int i=0; i<8; i++ )
{
srand(time( NULL));
a=rand()%17;
strcat(str,str[i]);
}
str[strlen(str) - 1] = '\0'
return str;
}
通过其他函数调用这个函数就可以了
我来回复