繁体   English   中英

CI中的LPCWSTR问题应该是程序崩溃了

[英]LPCWSTR issue in C I suppose, Program is crashing

我正在尝试接受用户输入,并在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将输入存储在字符数组中?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM