[C6064]警告以及解决方法

本文介绍如何使用scanf_s()函数安全地从标准输入读取数据,避免因边界问题导致的安全隐患。通过一个结构体传参的例子展示了正确的用法,并对比了scanf()的潜在风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于函数scanf_s();

当出现C6064这个警告的时候,预示着缺少一个整形参量,该参量的功能是表明输入字符的长度(可以使用sizeof,strlen 等函数);

例子如下:

scanf_s("%s", book.title,sizeof(book.title));


完整源代码如下:

(结构体传参的测试)

#include<stdio.h>



struct Date

{

int year;

int month;

int day;

};

struct Book

{

char title[128];

char auther[40];

float price;

struct Date date;

char publisher[40];

};



struct Book GetInput(struct Book book)

{

printf_s("请输入书名:");

scanf_s("%s", book.title,sizeof(book.title));

printf_s("请输入作者:");

scanf_s("%s", book.auther,sizeof(book.auther));

printf_s("请输入售价:");

scanf_s("%f", &book.price);

printf_s("请输入出版日期:");

scanf_s("%d-%d-%d", &book.date.year, &book.date.month, &book.date.day);

printf_s("请输入出版社:");

scanf_s("%s", book.publisher,sizeof(book.publisher));



return book;

}



void printBook(struct Book book)

{

printf_s("书名 :%s \n", book.title);

printf_s("作者 :%s \n", book.auther);

printf_s("售价 :%f \n", book.price);

printf_s("出版日期 :%d-%d-%d\n", book.date.year, book.date.month,book.date.day);

printf_s("出版社 :%s\n", book.publisher);

}



int main()

{

struct Book b1={0}, b2={0};

printf_s("请输入第一本书的信息...");

putchar('\n');

b1 = GetInput(b1);

printf_s("请输入第二本书的信息...");

b2 = GetInput(b2);

printf_s("录入完毕,现在输出:\n");

printf_s("第一本书的信息:\n");

printBook(b1);

printf_s("第二本书的信息:\n");

printBook(b2);

return 0;

}

输入使用 scanf() ,是不安全的,因为他在读取字符串的时候不会检查边界,可能会造成内存泄露,在 Visual Studio 中编译会报错,推荐使用 scanf_s() 。

### 解决 C6064 错误:`scanf` 缺少整型参数 编译器报告 `C6064` 错误表示在调用 `scanf` 函数时,传递给它的参数不符合预期。具体来说,当指定了 `%d` 或其他用于读取整数的格式说明符时,却没有提供相应的指向整数变量的地址作为参数。 #### 正确使用 `scanf` 为了修正此错误,在调用 `scanf("%d", ...)` 时应确保提供了有效的指向整数类型的指针。下面是一个简单的例子来展示如何正确地使用 `scanf` 来接收用户输入并存储到一个整数变量中: ```c #include <stdio.h> int main() { int number; printf("Enter an integer: "); // 注意这里传入的是 &number 而不是 number scanf("%d", &number); printf("You entered: %d\n", number); return 0; } ``` 上述代码片段展示了如何通过向 `scanf` 提供适当类型的指针来避免 `C6064` 错误[^1]。 此外需要注意的是,如果程序中有多个要读取的数据项,则每种数据类型都应当匹配对应的格式字符串部分,并且按照顺序依次给出相应变量的地址。例如: ```c float fValue; char cChar; printf("Input float and char separated by space:"); scanf("%f %c", &fValue, &cChar); // 输出结果验证 printf("Float value is %.2f and character is '%c'\n", fValue, cChar); ``` 在这个例子中,对于浮点数和字符类型的输入,分别用了 `%f` 和 `%c` 的格式化描述符,并且同样为它们各自准备了一个合适的内存位置以便保存所获取的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljl2107

感谢我能帮助到你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值