我正在使用系统,从特定键盘读取一些符号,将其传递给 ATmega8,然后将其逐个传递给显示器(此步骤正常工作),但如果我想显示所有符号数组,我发现第一个位置的动态数组保存空,第二个保存空符号,并且正确保存了后续字符。我没有看到代码中有任何错误,所以我需要帮助。
此代码函数必须返回从键盘读取串行符号的 4 元素 char 数组。
char* askPass(void){
int i;
char key;
#define PS 4
char* pass = (char*)calloc(PS, sizeof(char));
clear:
lcd_clear();
lcd_gotoxy(0, 0);
lcd_puts("Enter the password:");
lcd_gotoxy(0, 1);
lcd_puts(">>");
free(pass);
pass = (char*)calloc(0, sizeof(char));
for (i=0;i<PS;i++) pass[i] = '';
for (i=0; i<PS; i++) {
key = '-';
key = readKey();
lcd_gotoxy(3+i, 1);
if (key == 'C') {
goto clear;
} else if (key == '-'){
lcd_putchar('|');
delay_ms(10);
lcd_gotoxy(3+i, 1);
lcd_putchar(' ');
delay_ms(10);
lcd_gotoxy(3+i, 1);
i--;
} else {
pass = (char*)realloc(pass, i*sizeof(char));
*(pass+i) = key;
lcd_putchar(*(pass+i));
delay_ms(20);
}
}
/// there is an error:
/// serial input: 1234
/// lcd output: !* 34!
/// correct output: !1234!
lcd_gotoxy(0,2);
lcd_puts("!");
for (i=0; i<PS; i++) {
if (!(*(pass+i))) lcd_putchar('*');
else lcd_putchar(*(pass+i));
}
lcd_puts("!");
// end error block
return pass;
} // can't return correct array value
/* 所有测试都表明:
Serial input word: abcd
Output: !* cd!
Correct output: !abcd!
*/