Returns a "string" from a stream
I am using streams and I want the stream to read a string and return it in main, so I can use it mostly. Could you help me? This is what I am doing, but it shows strange characters in the output:
Topic:
char *usr=malloc(sizeof(char)*10);
[...code...]
return (void*)usr;
home:
[...code...]
char usr[10];
pthread_join(login,(void*)&usr);
printf("%s",usr);
+3
source to share
1 answer
Allows to allocate some memory in a thread function and copy some string to that memory.
Then, return a pointer to that memory from the thread function.
In the main function to get the return value of this stream function use pthread_join()
, you need to enter the receiver value as(void**)
see below code.
#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;
pthread_create(&th1, NULL, incer, NULL);
pthread_join(th1, (void**)&temp);
printf("temp is %s",temp);
return 0;
}
Is this what you want.
+3
source to share