C编程书错还是编程错误?
C Programming Book Error or Programming Error?
int main()
{
// Initialize & Declare variable
int m = 5;
// Allocates memory for storage of an integer variable
int *itemp;
// Stores memory address of variable m in memory address itemp
itemp = &m;
// Notice after declaring pointer you don't need to reference it as a pointer
// asterick is also known as indirection operator
// indirect reference: Accessing the contents of a memory cell through a pointer variable that stores it's address
// We can rewrite the contents in the memory cell as such
*itemp = 35;
printf("%d",*itemp);
// Doubles the value of m
*itemp = 2 * *itemp;
printf("%d",*itemp);
return 0;
}
它返回 3570
而不是 70
,这是书上说它应该返回的。我做错了什么?
程序正确。它正在打印编码要打印的内容。
为了澄清,
- 您有两个
printf()
,打印 35
和 70
。
- 您的
printf()
中没有 "seperator" [例如 newline (\n
)] 来区分两个打印语句的输出。
结果:您看到的最终输出 3570
是两个打印语句 35
和 70
.
输出的组合
解决方案:在 printf()
中提供的格式字符串末尾添加一个 \n
或 \t
以在其后添加一个可视的 分隔符 每个 printf()
以避免混淆。
随心所欲
printf("%d\n",*itemp);
您在同一行中看到 35 和 70 作为输出,或者在它们之间添加一个 space 或一个换行符。
int main()
{
// Initialize & Declare variable
int m = 5;
// Allocates memory for storage of an integer variable
int *itemp;
// Stores memory address of variable m in memory address itemp
itemp = &m;
// Notice after declaring pointer you don't need to reference it as a pointer
// asterick is also known as indirection operator
// indirect reference: Accessing the contents of a memory cell through a pointer variable that stores it's address
// We can rewrite the contents in the memory cell as such
*itemp = 35;
printf("%d",*itemp);
// Doubles the value of m
*itemp = 2 * *itemp;
printf("%d",*itemp);
return 0;
}
它返回 3570
而不是 70
,这是书上说它应该返回的。我做错了什么?
程序正确。它正在打印编码要打印的内容。
为了澄清,
- 您有两个
printf()
,打印35
和70
。 - 您的
printf()
中没有 "seperator" [例如 newline (\n
)] 来区分两个打印语句的输出。
结果:您看到的最终输出 3570
是两个打印语句 35
和 70
.
解决方案:在 printf()
中提供的格式字符串末尾添加一个 \n
或 \t
以在其后添加一个可视的 分隔符 每个 printf()
以避免混淆。
随心所欲
printf("%d\n",*itemp);
您在同一行中看到 35 和 70 作为输出,或者在它们之间添加一个 space 或一个换行符。