【问题标题】:LPCWSTR issue in C I suppose, Program is crashing我想 C 中的 LPCWSTR 问题,程序正在崩溃
【发布时间】:2019-11-26 10:31:30
【问题描述】:

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

顺便说一句,我在网上和这里找到的大部分代码都被 sn-ps 泄露了。

【问题讨论】:

    标签: c user-input createprocess


    【解决方案1】:
    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 将输入存储在字符数组中?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2017-06-23
      • 2014-04-28
      相关资源
      最近更新 更多