您好,提前致谢
简而言之,我所做的是创建一个指针,它在堆栈上创建一个局部变量,然后我通过 malloc 请求内存,它在堆中分配空间。
然后我在堆栈上创建一个本地 int。
然后我通过 scanf 请求用户输入。
但是在输入最后一位数字后,即使我尝试通过 getchar() 保留它,控制台也消失了并且不向我打印结果
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 80
int main()
{
char *student = malloc(MAX_LINE * sizeof(char));
int grade;
printf("Enter students name ");
scanf("%s", student);
printf("Enter students grade ");
scanf("%d", grade);// i would say it has to be grade and not &grade
// it vanishes right after here. Cant get to see any result
printf("%s received a %d\n", student, grade);
free(student);
getchar();
}
最佳答案
scanf("%d", grade);
应该是 scanf("%d", &grade);
您应该传递要存储输入元素的变量/缓冲区的地址。而 grade
指的是内容,&
addressof operator operation on grade
&grade
给我们的地址多变的。
在 scanf("%s", student);
的情况下,student
本身引用地址,即指针变量 student< 的内容
其中包含您刚刚分配的内存块的基地址。因此这是正确的。
参数应始终指向您希望 scanf
放置该输入的特定部分的变量/缓冲区位置的地址。
假设最初你在grade
中存储了垃圾0x5964
,grade
的内存地址是0x1234abcd
.在 scanf ("%d", grade);
中,scanf
会尝试将读取的整数写入内存位置 0x5964
,即无效。
而在 scanf ("%d", &grade);
中,scanf
会将读取的整数存储到内存位置 0x1234abcd
。在将 grade
称为 r-value 之后,您将获得内存位置 0x1234abcd
上的内容,这就是您想要的。
+----------+
| 0x5964 | <-------(uses this as address)---+-------------------+
+----------+ <------+ | |
| grade | (writes) scanf ("%d", grade); |
+----------+ (here) scanf ("%d", &grade); |
|0x1234abcd| | | |
+----------+ <------+(uses this as address)---+ |
|
|
+----------+ |
| ?????? | <----------(tries to write here)----------------------+
+----------+
| ??? |
+----------+
| 0x5964 |
+----------+
关于C、指针、控制台在输入数据后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6323201/