【发布时间】:2019-06-07 05:02:28
【问题描述】:
我真的很努力想弄清楚如何将字符串从一个函数返回给另一个函数。请帮我解决这个问题。
从这个函数返回密码作为字符串:
char* password(void) {
const maxPassword = 15;
char password[maxPassword + 1];
int charPos = 0;
char ch;
printf(
"\n\n\n\tPassword(max 15 Characters/no numeric value or special char is allowed):\t");
while (1) {
ch = getch();
if (ch == 13) // Pressing ENTER
break;
else if (ch == 32 || ch == 9) //Pressing SPACE OR TAB
continue;
else if (ch == 8) { //Pressing BACKSPACE
if (charPos > 0) {
charPos--;
password[charPos] = '\0';
printf("\b \b");
}
} else {
if (charPos < maxPassword) {
password[charPos] = ch;
charPos++;
printf("*");
} else {
printf(
"You have entered more than 15 Characters First %d character will be considered",
maxPassword);
break;
}
}
} //while block ends here
password[charPos] = '\0';
return password;
}
到这个功能(但它不打印):
void newuser(void) {
int i;
FILE *sname, *sid;
struct newuser u1;
sname = fopen("susername.txt", "w");
if (sname == NULL) {
printf("ERROR! TRY AGAIN");
exit(0);
}
printf("\n\n\n\tYourName:(Eg.Manas)\t"); //user name input program starts here
scanf("%s", &u1.UserName);
for (i = 0; i < strlen(u1.UserName); i++)
putc(u1.UserName[i], sname);
fclose(sname);
//sid=fopen("sid.txt","w");
printf("\n\n\n\tUserId:(Eg.54321)\t"); //User Id input starts here
scanf("%d", &u1.UserId);
printf("%s", password());
}
【问题讨论】:
-
您基本上是将地址返回给函数结束时超出范围的局部变量。
malloc或使其成为static。另请注意,您返回的不是字符串文字。 -
此代码中没有返回字符串文字。文字是由其值命名的事物,例如
3表示 3 或"abc"表示由“a”、“b”和“c”组成的字符串。函数试图返回password的东西是char的数组,而不是字符串文字。 -
旁白:
else if (ch == ' ' || ch == '\t')或else if (ch == 32 || ch == 9) //Pressing SPACE OR TAB哪个更容易编码/阅读?