GetConsoleCursorInfo在Windows 7 SP1上崩溃

问题描述

我正在尝试在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构建工具成功构建了此代码,尽管运行始终会崩溃。我该如何解决

解决方法

您的代码中有几个问题。

这是带注释的更正代码:

#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());
}