回 帖 发 新 帖 刷新版面

主题:返回字符串的初级问题?

我想做一个返回字符串的函数,可是下面的代码一执行程序就死了

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个回复)

沙发

strcat(str[100],str[i]) 你的两个参数的问题

板凳

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 楼

我理解你的意思应该写成这样:(但整个代码我没看出来你想表达什么)
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 楼

这样写可以.

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;
}
通过其他函数调用这个函数就可以了

我来回复

您尚未登录,请登录后再回复。点此登录或注册