我正在尝试接受用户输入,并在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;
}


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

最佳答案

LPCWSTR drive[2];


您为两个指针分配空间。

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


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

LPCWSTR pPath;


好的,pPath是尚未指向任何内容的指针。您所拥有的只是一个指针。

wscanf(L"%s", &pPath);


您应该告诉wscanf将输入的字符串存储在哪里。但是您从来没有为字符串分配空间,只是创建了一个不指向任何内容的指针。

这是我可以从wscanf的第一个示例获得的一些代码:

  wchar_t str [80];
  int i;

  wprintf (L"Enter your family name: ");
  wscanf (L"%ls",str);


请注意,它是如何为80个宽字符数组分配空间的,然后告诉wscanf将输入存储在字符数组中?

关于c - 我想C中的LPCWSTR问题,程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59048868/

10-12 21:49