首页 > 解决方案 > 将字符串数组作为参数传递给 WinAPI 的线程函数的问题

问题描述

任务是这样的:要使用 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;
}```

标签: c++arraysstringmultithreadingwinapi

解决方案


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

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

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


推荐阅读