I am wondering what am I doing wrong here? I cast the void pointer into a struct buffer and it only prints out garbage. Shouldn’t buffer now point to ptr that is a pointer back to the original buffer that we allocated memory for?
#include <stdio.h>
#include <pthread.h>
struct buffer{
int a;
char *string[];
}buffer;
void thread1_function(void *ptr){
struct buffer *buffer=(struct buffer*)ptr;
printf("hello world\n");
printf("%s-%n\n", buffer->string,buffer->a);
}
int main(){
struct buffer *buffer;
int err;
buffer = (struct buffer*)malloc((11*sizeof(char))+sizeof(int));
pthread_t thread1;
sprintf(buffer->string,"%s","strint");
buffer->a=1;
printf("main: %s - %d\n",buffer->string,buffer->a);
err = pthread_create(&thread1, NULL, thread1_function, &buffer);
printf("error: %d\n",err);
pthread_join(thread1,NULL);
return 0;
}
~
You pass the pointer to the pointer to the struct to your thread. Try passing the pointer to the struct instead. 😉
becomes
EDIT:
Found another mistake:
printf("...%n")in the thread function.%nindicates to store the number written so far into the position, theint*parameter at that position points to. You obviously mean%dthere, as in yourmain().