[英]C programming: scanf for char pointer not working
我有一个程序可以接收用户输入的教室和时间。 课堂输入存储在char *教室内部,时间存储在int时间内部。 但是,当我运行该程序时,键入教室后,按Enter键时该程序停止。 “请输入时间:”的printf没有出来。 为什么会这样呢?
void option1()
{
char* classroom;
int time;
printf("Please enter the classroom: ");
scanf_s("%s", &classroom);
printf("Please enter the time: ");
scanf_s("%d", &time);
}
感谢帮助 :)
正如我已经评论过的,此代码段中存在很多错误:
scanf_s
与scanf
,它需要其他大小参数。 我建议不要使用它。 scanf()
仅使用"%s"
,您需要指定字段宽度以防止缓冲区溢出。 (这与scanf_s()
不同,因为缓冲区大小是那里的一个附加参数。) classroom
)写入数据,您需要分配内存! (通过将其设置为数组或通过调用malloc()
)。 纠正了这些错误的代码段可能如下所示:
void option1()
{
char classroom[128];
int time;
printf("Please enter the classroom: ");
scanf("%127s", classroom);
// field width is one less than your buffer size,
// because there will be a 0 byte appended that terminates the string!
printf("Please enter the time: ");
scanf("%d", &time);
}
创建变量作为指针并为其分配内存,或者分配char数组并将其传递给scanf。
//Use of array
char classroom[10];
scanf("%9s", classroom);
//Use of heap
char* classroom = malloc(10 * sizeof(*classroom));
scanf("%9s", classroom);
//Use your variable classroom here, when done, call free to release memory.
free(classroom);
此处的字符串长度为9
以防止缓冲区溢出和越界写入。 数组的大小为10
元素。
使用scanf
代替scanf_s
,为char指针分配内存,并且不使用&
,它已经是指针。 请参见下面的示例:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int time;
char* classroom;
classroom = malloc(sizeof(char) * 1024);
if(classroom == NULL)
{
fprintf(stderr, "Failed to allocate memory!\n");
exit(1);
}
printf("Please enter the classroom: ");
scanf("%s", classroom);
printf("Please enter the time: ");
scanf("%d", &time);
printf("\nClassroom: %s\n", classroom);
printf("Time: %d\n", time);
free(classroom); //Free the memory
return 0;
}
scanf
系列函数将格式字符串指定的数据读入作为参数提供的变量。
这些函数不会为字符串变量分配存储空间! 在没有分配内存的情况下为scanf提供可变的classroom
,将使scanf尝试将数据放置在内存中的未定义位置。 这可以导致任何类型的行为,通常称为未定义行为 。
因此,您必须首先为字符串变量分配存储,例如:
char*classroom= malloc(1024);
现在您可以使用它调用scanf:
scanf_s("%s", classroom);
请注意,由于char指针的行为就像一个数组(即,它指向char的数组),因此您不必使用运算符&
的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.