我想C中的LPCWSTR问题,程序崩溃了

问题描述 投票:0回答:1

我正在尝试接受用户输入,并在CreateProcessW()函数中使用它。简单地说,用户放入应用程序的路径,然后程序将其打开。但它崩溃了。任何帮助。一切都可以编译。

#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <processthreadsapi.h>
#include <errno.h>



void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}

int main(int argc,char *argv[])
{

    LPCWSTR drive[2];

    printf("\nEnter the drive, do not include '\\' (Ex. C:) : ");
    wscanf(L"%s", drive);

    LPCWSTR path = L"\\Windows\\notepad.exe";

    STARTUPINFOW siStartupInfo; 
    PROCESS_INFORMATION piProcessInfo; 

    memset(&siStartupInfo, 0, sizeof(siStartupInfo)); 
    memset(&piProcessInfo, 0, sizeof(piProcessInfo)); 

    siStartupInfo.cb = sizeof(siStartupInfo); 

    LPCWSTR pPath;

    wprintf(L"%ls%ls\n", drive, path);
    printf("\nPlease enter the path exact as shown above: ");
    wscanf(L"%s", &pPath);

    printf("\nNow opening notepad . . . . \n\n");
    delay(3000);

    if (CreateProcessW(pPath, 
                        NULL, 
                        NULL, 
                        NULL, 
                        FALSE, 
                        0, 
                        NULL, 
                        NULL, 
                        &siStartupInfo, 
                        &piProcessInfo)) 
    {
        printf("Notepad opened. . .\n\n");
    }
    else 
    {
        printf("Error = %ld\n", GetLastError());
    }

    return 0;
}

顺便说一句,大多数代码都是我在网上和此处找到的摘录的摘要。

c user-input createprocess
1个回答
0
投票
LPCWSTR drive[2];

您为两个指针分配了空间。

printf("\nEnter the drive, do not include '\\' (Ex. C:) : ");
wscanf(L"%s", drive);

糟糕,您正在告诉wscanf将字符串存储在您分配的空间中。但是您只为两个指针分配了空间。

LPCWSTR pPath;
// ...
wscanf(L"%s", &pPath);

您需要传递wscanf您要在其中存储字符串的地址,而不是特别指向没有内容的指针的地址。

© www.soinside.com 2019 - 2024. All rights reserved.