我想知道为什么下面的代码如下所示。我第一次打印变量“account_name”时它工作正常。第二次和第三次,它根本不起作用,而是打印乱码。我是C的初学者。
const char * get_account_name(){
char loc_account_name[255];
printf ("Please enter the ledger Account name: ");
scanf ("%[^\n]", &loc_account_name);
fflush(stdin);
printf ("\n");
return ( loc_account_name );
}
void main (void)
{
/* Declare variables. We use the predefined "MAX_ENTRIES" definition to define how large the arrays will be */
float credits[MAX_ENTRIES], debits [MAX_ENTRIES], starting_balance, ending_balance;
int debit_amount, credit_amount, x;
char * account_name;
printf ("Welcome to the Sears Ledger System\n\n");
/* Prompt the user to enter the name of the account, we allow for up to 255 characters and account for names with spaces as well */
account_name = get_account_name();
printf("%s",account_name);
printf("%s",account_name);
printf("%s",account_name);
} /* end main*/
*更新
我已经删除了 get_account_name 函数的 scanf 中的 & 符号。然后我发现它会多次打印出正确的值,但是此后程序永远挂起。不幸的是,我被迫使用的编译器没有调试器,所以我仍然对正在发生的事情感到困惑。
char * get_account_name(){
char * loc_account_name;
printf ("Please enter the ledger Account name: ");
scanf ("%[^\n]", loc_account_name);
fflush(stdin);
printf ("\n");
return loc_account_name;
}
* *更新2
char *get_account_name() {
char loc_account_name[255];
char *r;
printf ("Please enter the ledger Account name: ");
scanf ("%[^\n]", &loc_account_name);
fflush(stdin);
printf("%s\n", loc_account_name);
*r = malloc(strlen(loc_account_name) + 1);
strcpy(r, loc_account_name);
return r;
}
void main (void)
{
char * account_name;
/* Prompt the user to enter the name of the account, we allow for up to 255 characters and account for names with spaces as well */
account_name = get_account_name();
printf("%s\n", account_name);
printf("%s\n", account_name);
printf("%s\n", account_name);
free(account_name);
} /* end main*/