天天看點

c語言的一處陷阱

實際碰到的一個問題,從MSDN上拷貝了一段代碼,是用C寫的,編譯通過,執行崩潰, ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

#include <WINDOWS.H>

// test.c 用Unicode方式編譯崩潰

void

main()

{

STARTUPINFO si;

PROCESS_INFORMATION pi;

ZeroMemory( &si, sizeof(si) );

si.cb = sizeof(si);

ZeroMemory( &pi, sizeof(pi) );

if

( !CreateProcess( NULL,  

// No module name (use command line)

"calc.exe"

,       

// Command line

NULL,          

// Process handle not inheritable

NULL,          

// Thread handle not inheritable

FALSE,         

// Set handle inheritance to FALSE

,             

// No creation flags

NULL,          

// Use parent's environment block

NULL,          

// Use parent's starting directory 

&si,           

// Pointer to STARTUPINFO structure

&pi )          

// Pointer to PROCESS_INFORMATION structure

WaitForSingleObject( pi.hProcess, INFINITE );

// Close process and thread handles. 

CloseHandle( pi.hProcess );

CloseHandle( pi.hThread );

}

以上代碼用unicode方式c編譯可以通過,運作時崩潰,編譯器會報個警告,兒非錯誤

test.c(13) : warning C4133: 'function' : incompatible types - from 'char [9]' to 'LPWSTR'

CreateProcessW 的第二個參數要去是LPWSTR ,這裡被強制轉換了而c++方式編譯的話會報錯,直接編譯不過

test.cpp(21) : error C2664: 'CreateProcessW' : cannot convert parameter 2 from 'const char [9]' to 'LPWSTR'