【发布时间】:2020-02-21 21:15:45
【问题描述】:
所以,我试图从 char* 函数返回一个字符串,但我总是收到此警告:函数返回局部变量 [-Wreturn-local-addr] 的地址,并且该字符串不会打印到控制台.
昨天我尝试 printf(password = createPassword(quantity) 并且成功了,但是当我今天再次尝试时,它没有打印字符串。
这是功能
char* createPassword(int a){
char contadorTotal = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0,password[30000] = "", randomChar, temp[100000];
int random;
srand((unsigned)time(NULL));
while (a > 0)
{
do
{
random = (rand()%(5-1)) + 1;
if(random == 1){
if(c1 < 4){
randomChar = (33 + rand() % (48-33));
sprintf(temp, "%c", randomChar);
strcat(password, temp);
c1++;
contadorTotal++;
}
}else if(random == 2){
if(c2 < 3){
randomChar = rand() % 26 + 97;
sprintf(temp, "%c", randomChar);
strcat(password, temp);
c2++;
contadorTotal++;
}
}else if( random == 3){
if(c3 < 3){
randomChar = (65 + rand() % (91-65));
sprintf(temp, "%c", randomChar);
strcat(password, temp);
c3++;
contadorTotal++;
}
}else if(random == 4){
if(c4 < 3){
randomChar = (48 + rand() % (58-48));
sprintf(temp, "%c", randomChar);
strcat(password, temp);
c4++;
contadorTotal++;
}
}
}while (contadorTotal < 13);
a--;
c1 = 0;
c2 = 0;
c3 = 0;
c4 = 0;
contadorTotal = 0;
strcat(password, "\n");
}
return password;
}
这就是我要打印结果的地方
case 'c':
int quantity;
char* password;
printf("Insert how many passwords you want to create: ");
scanf("%d", &quantity);
printf("----------------------\n");
password = createPassword(quantity);
printf(password);
break;
}
结果应该是打印在控制台上的密码,但它什么也没显示。
【问题讨论】:
-
return strdup(password);在函数的末尾,free(password);在你完成后在调用者中。 -
简单修复:
static char password[30000];。 (但你真的需要这么大的数组吗?) -
尝试重写您的函数,使其接收存储密码的指针,而不是将密码存储在自己的本地数组中。
int createPassword(int a, char *destination) { /* your code using destination to store password */ }并这样称呼它:char password[100]; int quantity; ... if (quantity < 100) createPassword(quantity, password); -
我使用了 mch 解决方案,效果很好,非常感谢大家!我可能需要学习一些 C 课程才能变得更好!