【问题标题】:GetConsoleCursorInfo crashes on Windows 7 SP1GetConsoleCursorInfo 在 Windows 7 SP1 上崩溃
【发布时间】:2021-02-04 11:33:32
【问题描述】:

我正在尝试在我的 win7 sp1 上打印 ConsoleCursorInfo。

#include <windows.h>
#include <stdio.h>
int main(){
    printf("xp SetConsoleCursorInfo\n");
    CONSOLE_CURSOR_INFO *CURSOR;
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleCursorInfo(hStdout, CURSOR);
    printf("%u",CURSOR->dwSize);
}

我使用 vs2019 构建工具成功构建了此代码,但运行它总是崩溃。我该如何解决?

【问题讨论】:

  • 如果 GetStdHandle 返回 INVALID_HANDLE_VALUE 会发生什么。也许您应该检查 GetStdHandle 的返回值?
  • CURSOR 无处可去。 CONSOLE_CURSOR_INFO *CURSOR -> CONSOLE_CURSOR_INFO cursorGetConsoleCursorInfo(hStdout, CURSOR) -> GetConsoleCursorInfo(hStdout, &amp;cursor);。顺便说一句,不要使用所有大写标识符。
  • 不要忽略编译器警告:使用了未初始化的局部变量 'CURSOR'
  • 请注意警告使用未初始化的局部变量'FooBar'几乎总是一个错误,应该相应地处理。

标签: c windows windows-console


【解决方案1】:

您的代码中有几个问题。

这是您使用 cmets 更正的代码:

#include <windows.h>
#include <stdio.h>

int main(){
    printf("xp SetConsoleCursorInfo\n");
    CONSOLE_CURSOR_INFO cursor;  // we need a CONSOLE_CURSOR_INFO and not 
                                 // a pointer to CONSOLE_CURSOR_INFO

    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    if (GetConsoleCursorInfo(hStdout, &cursor))   // check if GetConsoleCursorInfo fails
                                   // ^ and mind the & operator here
      printf("%u",cursor.dwSize);
    else
      printf("GetConsoleCursorInfo failed with error %d\n", GetLastError());
}

【讨论】:

    猜你喜欢
    • 2011-04-09
    • 1970-01-01
    • 2012-07-17
    • 2012-07-16
    • 1970-01-01
    • 2013-01-20
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多