【问题标题】:Problem with passing array of strings as argument to thread function of WinAPI将字符串数组作为参数传递给 WinAPI 的线程函数的问题
【发布时间】:2020-08-16 22:28:19
【问题描述】:

任务是这样的:要使用 shell 排序对字符串数组进行排序,应该使用 WinAPI 在线程函数中执行排序。最初,程序是使用全局变量编写的,但必须将字符串数组作为参数传递给线程函数,然后开始出现类型转换问题。

strcpy_s(strings[i], strings[i + step]); 上的错误错误日志:E0304 no instance of overloaded function "strcpy_s" matches the argument list

朋友,这个问题怎么解决?我认为整个问题是我如何将类型从 void* 转换为字符串数组。

#include<iostream>
#include<conio.h>
#include<iomanip>
#include <string.h>
#include <string> 
#include <Windows.h>
#include <process.h>

using namespace std;

const int row = 10, n = 32;

__int64 to_int64(FILETIME ft)
{
    return static_cast<__int64>(ft.dwHighDateTime) << 32 | ft.dwLowDateTime;
}

DWORD WINAPI shellSort(PVOID pParams) {
    int step = row / 2;
    char** strings = (char**)pParams;
    while (step > 0)
    {
        for (int i = 0; i < (row - step); i++) {
            while (i >= 0 && strcmp(strings[i], strings[i + step]) > 0)
            {
                char temp[n];
                strcpy_s(temp, strings[i]);
                strcpy_s(strings[i], strings[i + step]);
                strcpy_s(strings[i + step], temp);
                i--;
            }
        }
        step = step / 2;
    }
    return 0;
}

int main()
{
    int i;

    char strings[row][n];

    std::cout << "input " << row << " strings:\n";
    for (i = 0; i < row; i++) {
        cout << i + 1 << ". ";
        cin.getline(strings[i], n);
    }
    std::cout << "\nOurs strings:\n";
    for (i = 0; i < row; i++)
        printf("%s\n", strings[i]);
    printf("\n");

    HANDLE thread = CreateThread(NULL, 0, &shellSort, strings, 0, NULL);
    SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL);

    WaitForSingleObject(thread, INFINITE);

    FILETIME ft[4];
    GetThreadTimes(thread, &ft[0], &ft[1], &ft[2], &ft[3]);

    std::cout << (to_int64(ft[1]) - to_int64(ft[0])) << endl;

    printf("Sorted array:\n");
    for (i = 0; i < row; i++)
        printf("%s\n", strings[i]);
    getchar();
    return 0;
}```

【问题讨论】:

  • CreateThread: "可执行文件中调用 C 运行时库 (CRT) 的线程应使用 _beginthreadex_endthreadex 函数进行线程管理,而不是使用 @987654328 @ 和 ExitThread [...]"。并发是一个棘手的问题。勤奋是成功的先决条件。
  • 嗨 AleksMys,如果答案解决了您最初的问题,您可以 accept 它。对于新出现的问题,请随时提出新问题。

标签: c++ arrays string multithreading winapi


【解决方案1】:

strcpy_s 接受三个参数。也许您打算改用strcpy

            strcpy(temp, strings[i]);
            strcpy(strings[i], strings[i + step]);
            strcpy(strings[i + step], temp);

在这里转换void* 没有问题。您只是为正在调用的函数使用了错误数量的参数。

【讨论】:

  • @ale 提交答案后,请勿将您的问题更改为其他问题。如果您有新问题,请单击 按钮。我回滚了你的编辑。
猜你喜欢
  • 2012-07-26
  • 2010-10-03
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
相关资源
最近更新 更多