WriteConsole访问在功能调用中违反,而不是来自main()
WriteConsole access violation in function call but not from main()
我试图在函数调用中使用WriteConsole(..(,但我受到访问违规。当我以主机为单位时,它将我的文本打印到屏幕上,在主函数中没有任何问题。当我尝试在函数调用中打印字符串时,即使它确实将文本打印到控制台。
void print(char *_charArray);
int _tmain(int argc, _TCHAR* argv[])
{
HWND hConsole;
// HANDLE hFile;
char myText[] = "This is my text";
char *pMyText = myText;
LPDWORD charsWriten;
// hFile = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_READ, NULL,
// OPEN_EXISTING, 0, NULL);
print(pMyText);
// WriteConsole(hFile, myText, sizeof(myText), charsWriten, NULL);
getch();
return 0;
}
void print(char *text)
{
LPDWORD charsWriten;
HANDLE hFile;
hFile = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
unsigned int strn = strlen(text) + 1;
if(!WriteConsole(hFile, text, (strlen(text) + 1), charsWriten,NULL))
{
printf("Write Failedn");
}
}
此声明是错误的:
LPDWORD charsWriten;
CreateFile
函数期望第四参数是可以写入变量的指针。但是,您实际上并没有分配内存;您只是声明了一个指针,这是一个非专业化的指针。那行不通。您需要做:
DWORD charsWritten;
...
WriteConsole(hFile, text, (strlen(text) + 1), &charsWritten, NULL)
将解决访问违规问题,但它并不能解释为什么您要在字符串末端编写一个字符。您无需将1添加到strlen
;终止不需要编写。
LPDWORD charsWriten;
LPDWORD
是DWORD*
。因此,您拥有的是一个非初始化的指针。然后,您将此指针传递给WriteConsole
,该指针将其写入指向的无效位置。相反,将charsWritten
声明为类型DWORD
,并使用&charsWritten
将其地址传递给WriteConsole
。
DWORD charsWritten;
WriteConsole(hFile, text, (strlen(text) + 1), &charsWritten, NULL);
,如您所说,它可以正常工作。那简直是厄运。这是不确定的行为,并不总是具有可预测的结果。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- "no main"用于C++中链接或执行的功能
- 无法从Linux,C ++执行"my_script" python脚本"main(filename)"功能;pModule = PyImport_Import(pName);返回空值
- 在功能中创建一个数组,然后将其返回到main()
- WriteConsole访问在功能调用中违反,而不是来自main()
- C 将用户输入从一个函数到另一个功能,并使用Main(Newbie)显示
- 在C 中使用静态功能,我的教授希望我告诉Main哪个对象具有最高优先级,而无需传递任何内容
- 将功能与"int main"问题分开(初学者)
- 在功能方面遇到了一些问题,以及它们如何干扰Main
- 在QT Main功能中,Qapplication如何了解MainWindow
- 我有一个构造函数,但我需要将输出返回到 main.cpp.我无法使用获取字符串功能!!任何想法如何实现这一目标?
- 无法在Main之外创建2个功能
- 如何使用Google测试在Main()函数中的特定位置调用特定的测试功能
- 将某些功能与 main.cpp 分离时出现"undefined symbols for architecture"错误,该怎么办?
- 我正在使用Xcode进行c ++编程和学习。为什么我不能在一个项目中放置许多具有 MAIN 功能的单独源文件?
- C++声明"main"作为对功能的引用?
- 在VS2010上拥有多个项目和多个"main"功能
- Makefile,使用mpiCC编译器为main.cpp和g++为其他功能的src代码
- 需要'return to main menu' C++代码中的功能