C 返回一个";“字符串”;从一根线

C 返回一个";“字符串”;从一根线,c,string,casting,pthreads,return,C,String,Casting,Pthreads,Return,我正在使用线程,我希望一个线程读取一个字符串并将其返回给main,这样我就可以在main中使用它。你能帮助我吗?我就是这么做的,但在输出中它显示了奇怪的字符: 线程: char *usr=malloc(sizeof(char)*10); [...code...] return (void*)usr; 主要内容: 让我们在线程函数中分配一些内存,并在该内存中复制一些字符串 然后从线程函数返回该内存的指针 在main函数中,要接收该线程函数的返回值,请使用pthread\u join()您需要键入

我正在使用线程,我希望一个线程读取一个字符串并将其返回给main,这样我就可以在main中使用它。你能帮助我吗?我就是这么做的,但在输出中它显示了奇怪的字符:

线程:

char *usr=malloc(sizeof(char)*10);
[...code...]
return (void*)usr;
主要内容:


让我们在线程函数中分配一些内存,并在该内存中复制一些字符串

然后从线程函数返回该内存的指针

在main函数中,要接收该线程函数的返回值,请使用
pthread\u join()
您需要键入cast,将接收器值转换为
(void**)

请参阅下面的代码


#包括
#包括
#包括
#包括
空虚*
增量(无效*arg)
{
龙我;
char*usr=malloc(25);
strcpy(usr,hello world\n);
返回usr;
}
内部主(空)
{
pthread_t th1,th2;
char*temp=NULL;
pthread_create(&th1,NULL,incer,NULL);
pthread_join(th1,(void**)和temp);
printf(“温度为%s”,温度);
如果(温度!=NULL)
免费(临时);
返回0;
}
这就是你想要的。

你可以这样试试

#include <iostream>
#include <future>
#include <exception>

std::string concatstring(const std::string& a,const std::string &b) {
    std::cout << __FUNCTION__ << "+" << std::endl;
    std::string c = a + b;
    std::cout << __FUNCTION__ << "-" << std::endl;
    return c;
    }

int main() {
    try {
        std::future<std::string> fps = std::async(concatstring,"Hello","world");
        if (fps.valid()) {
            std::cout << fps.get() << std::endl;
        }
    }
    catch (const std::exception &e) {
        std::cout << "Exception: " <<e.what() << std::endl;
    }
    return 0;
}
#包括
#包括
#包括
std::string concatstring(const std::string&a,const std::string&b){

std::我可以强烈怀疑OP代码失败的根本原因是
pthread_join()
的第二个参数的错误转换。这个问题只标记为与C相关。哦!我没有看到那个标记。
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>

void *
incer(void *arg)
{
    long i;

        char * usr = malloc(25);
        strcpy(usr,"hello world\n");
        return usr;
}


int main(void)
{
    pthread_t  th1, th2;
    char * temp = NULL;

    pthread_create(&th1, NULL, incer, NULL);


    pthread_join(th1, (void**)&temp);
    printf("temp is %s",temp);

    if(temp != NULL)
      free(temp);    
  
    return 0;
}
#include <iostream>
#include <future>
#include <exception>

std::string concatstring(const std::string& a,const std::string &b) {
    std::cout << __FUNCTION__ << "+" << std::endl;
    std::string c = a + b;
    std::cout << __FUNCTION__ << "-" << std::endl;
    return c;
    }

int main() {
    try {
        std::future<std::string> fps = std::async(concatstring,"Hello","world");
        if (fps.valid()) {
            std::cout << fps.get() << std::endl;
        }
    }
    catch (const std::exception &e) {
        std::cout << "Exception: " <<e.what() << std::endl;
    }
    return 0;
}