"static char" 与 C 中的 "char"

"static char" vs. "char" in C

为了练习变量声明、占位符和 I/O 调用,我在我用来学习的书中做了一个示例作业。但是,我将 运行 保留在一个特定的问题中,因为当我尝试为输入目的声明多个字符变量时,即使编译器没有捕获任何语法错误,执行时的程序也只会return 一个字符变量。这是有问题的代码:

#include <stdio.h>

int main()

{
double penny=0.01;
double nickel=0.05;
double dime=0.1;
double quarter=0.25;

double value_of_pennies;
double value_of_nickels;
double value_of_dimes;
double value_of_quarters;
double TOTAL;
int P;
int N;
int D;
int Q;
char a,b; 

//used "static char" instead of "char", as only using the "char" type caused a formatting error where only the latter character entered in its input would appear

printf("Please enter initials> \n");
printf("First initial> \n");
scanf("%s", &a);
printf("Second initial> \n");
scanf("%s", &b);

//"%s" was used as the input placeholder for type "char"

printf("%c.%c., please enter the quantities of each type of the following coins.\n", a, b);


printf("Number of quarters> \n");
scanf("%d", &Q);
printf("Number of dimes> \n");
scanf("%d", &D);
printf("Number of nickels> \n");
scanf("%d", &N);
printf("Number of pennies> \n");
scanf("%d", &P);

printf("Okay, so you have: %d quarters, %d dimes, %d nickels, and %d pennies.\n", Q, D, N, P);

value_of_pennies=penny*P;
value_of_nickels=nickel*N;
value_of_dimes=dime*D;
value_of_quarters=quarter*Q;

TOTAL=value_of_quarters+value_of_dimes+value_of_nickels+value_of_pennies;

printf("The total value of the inserted coins is $%.2lf. Thank you.\n", TOTAL);

//total field width omitted as to not print out any leading spaces
return(0);
}

这是转录输出("a","e",四个“1”是样本任意输入值:

Please enter initials>
First initial>
a
Second initial>
e
.e., please enter the quantities of each type of the following coins.
Number of quarters>
1
Number of dimes>
1
Number of nickels>
1
Number of pennies>
1
Okay, so you have: 1 quarters, 1 dimes, 1 nickels, and 1 pennies.
The total value of the inserted coins is [=13=].41. Thank you.

我输入了字符 "a" 和 "e" 作为字符变量 "a" 和 "b" 的输入值,但只显示了 "e"。另一方面,如果我在 "char" 变量声明中放置了 "static",那么两个输入的 char 值都将显示在相关的打印调用中。

为了以后参考,我想问一下为什么会这样,以及声明中"static"这个词的价值。

(顺便说一句,我知道我可以简单地将 "value_of_(insert coin here)" 变量设为常量宏。)

定义如

char a,b; 

写一个像

这样的语句
scanf("%s", &a);
scanf("%s", &b);

调用 undefined behaviour%s 不是 char 的格式说明符。使用错误的格式说明符会导致 UB。您应该使用 %c 扫描 一个 char.

详细说明,

  • %s 格式说明符需要一个相应的参数,该参数是指向 char 数组的指针。它 scan 是多个字符,直到遇到 space(空白字符,迂腐)或换行符或 EOF。
  • %c 格式说明符需要一个相应的参数,该参数是指向 char 变量的指针。它只从输入缓冲区读取一个char

因此,对于 %s,如果您提供 char 变量的地址,它将尝试访问超出分配的内存区域以写入 scanned 数据,这将调用 UB。

在继续之前,您可能想在 printf(), scanf() and format specifiers 上阅读更多内容。

您为 char 使用了错误的格式说明符。 char 使用 %c 而不是 %s。就 static 而言,我对你的问题有点困惑。您在评论中说您正在使用 static char,但我没有看到任何声明为 static char.

的变量