【发布时间】:2014-07-16 17:54:32
【问题描述】:
我正在使用 C++ 中的 WinApi 更改控制台属性并在最后两个函数中调用 GetConsoleScreenBufferInfo() 时出现分段错误错误。
奇怪的是,如果我在 main() 中重现相同的代码 - 只需使用相同的 HANDLE 和 PCONSOLE_SCREEN_BUFFER_INFO 声明调用 GetConsoleScreenBufferInfo() - 在 main() 中我没有收到错误,但如果我在 getPosCursorX() 中这样做,我仍然会得到错误。
命名空间控制台{
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
PCONSOLE_SCREEN_BUFFER_INFO infoCon;
struct TamanoConsola
{
COORD buffer;
SMALL_RECT ventana;
} inicial;
void gotoxy(int x, int y)
{
COORD dwPos;
dwPos.X=x;
dwPos.Y=y;
SetConsoleCursorPosition(hCon, dwPos);
}
void setColor(int texto, int fondo)
{
SetConsoleTextAttribute(hCon, fondo*16+texto);
}
void setBufferTamano(int ancho, int alto)
{
COORD buffertamano = {ancho, alto};
if(SetConsoleScreenBufferSize(hCon, buffertamano) == 0)
std::cout << "ERROR de WinApi numero: " << GetLastError() << std::endl;
}
void setVentanaTamano(int ancho, int alto)
{
SMALL_RECT ventanatamano1 ={0, 0, ancho-1, alto-1};
SMALL_RECT* ventanatamano = &ventanatamano1;
if(SetConsoleWindowInfo(hCon, TRUE, ventanatamano) == 0)
std::cout << "ERROR de WinApi numero: " << GetLastError() << std::endl;
}
void setVentanaBufferTamano(int anchoVentana, int altoVentana, int anchoBuffer, int altoBuffer)
{
setBufferTamano(anchoBuffer, altoBuffer);
setVentanaTamano(anchoVentana, altoVentana);
}
int getPosCursorX()
{
GetConsoleScreenBufferInfo(hCon, infoCon);
return infoCon->dwCursorPosition.X;
}
int getPosCursorY()
{
GetConsoleScreenBufferInfo(hCon, infoCon);
return infoCon->dwCursorPosition.Y;
}
}
提前致谢!
【问题讨论】:
-
你已经统一了指针 infoCon。
-
你没有为指针
infoCon分配内存。 -
@user2120666 未初始化,空指针(全局变量初始化为零)。
-
@JoachimPileborg:是的。谢谢指正。
-
你也完全忽略了错误检查和滥用全局变量。
标签: c++ windows winapi segmentation-fault