Visual Studio中创建的cpp项目语句里bug提示scanf语句的用法错误,不清楚原因在哪?

用的是Visual Studio Community 2017版本,创建了一个win32程序项目.cpp文件,bug提示程序里两行关于scanf语句的用法错误,原因不明。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 100
#define LIST_INIT_SIZE 4
#define OVERFLOW -1;
#define OK 1;
typedef int DataType;
typedef int Status;
typedef struct//定义顺序表
{
    DataType *elem;
    int length;
    int listsize;
}SeqList;
Status InitSeqList(SeqList **pL)//初始化顺序表
{
    SeqList *L;//将参数SeqList *L改为SeqList **pL,函数内部并多加一行用来定义SeqList类型的指针L。
    L = (SeqList*)malloc((LIST_INIT_SIZE) * sizeof(SeqList));//将L->elem改为L,将DataType改为SeqList。
                                        if (!L->elem)
        exit(-1);
    L->length = 0;
    L->listsize = LIST_INIT_SIZE;
    (*pL) = L;
    return OK;
}

int main()
{
    SeqList *List;
    InitSeqList(&List);
    int temp = 0;
    printf("请输入即将创建的顺序表的长度:\n");
    scanf("%d", &temp);
    List->length = temp;
    int i = 0;
    printf("请输入顺序表的数据元素:\n");
    for (; i < List->length; i++)
    {
        scanf("%d", &temp);* List->elem[i] = temp;
        //elem=elem+sizeof(DataType);
    }
    printf("顺序表的存储内容:\n");
    for (; i < List->length; i++)
    {
        printf("%d", (List->elem[i]));
        //elem=elem+sizeof(DataType);
    }
    return 0;
}

bug提示信息为:

1>------ 已启动生成: 项目: Project1, 配置: Debug Win32 ------
1>源.cpp
1>c:userslenovodocumentsvisual studio 2017projectsproject1project1源.cpp(45): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>c:program files (x86)windows kits10include10.0.15063.0ucrtstdio.h(1272): note: 参见“scanf”的声明
1>c:userslenovodocumentsvisual studio 2017projectsproject1project1源.cpp(51): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>c:program files (x86)windows kits10include10.0.15063.0ucrtstdio.h(1272): note: 参见“scanf”的声明
1>已完成生成项目“Project1.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

bug截图:

clipboard.png

自己有尝试着修改scanf括号里的语句用法,未果……

阅读 7.7k
4 个回答

不是说了scanf不安全让你用scanf_s替代么?
主要是scanf不会检查边界,比如
char in[2];
scanf("%s", in);//abcdef
这就越界了,然后崩了,类似的还有sprintf
不过scanf_s不是跨平台的,所以你保证不会越界,然后加_CRT_SECURE_NO_WARNINGS这个宏也可以

给编译命令行添加_CRT_SECURE_NO_WARNINGS就行了。

编译器提示的比较明显了,主要说一下后缀_s的版本,这是Windows C运行库对标准库的扩充,增加了一些安全的特性,如边界检查,s表示secure。既然你是CPP项目,你可以使用C++标准库的功能,比如std::cin。

scanf_s的参数表和scanf不一样。具体查MSDN。对于你这个程序,因为不是字符串,没有安全隐患,直接在最前面定义一下那个宏就可以了。
另外你的成语的另外一个问题是没有给指针elem指向的内存分配空间。
需要在循环里先malloc一个DataType给elem。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题