I am very new to c and write a small program where a struct will be created and assign some information to it.The code:
Code:
#include #include #include typedef struct data { int no; char *payload;} message;void new_message(message *msg, int no, char *str);int main(int argc, char** argv) { message msg1, msg2; char *str1 = "hello", *str2 = "world!"; new_message(&msg1, 1, str1); new_message(&msg2, 2, str2); printf("msg1 no: %d\n", msg1.no); printf("msg1 payload: %s\n", (&msg1)->payload); printf("msg2 no: %d\n", msg2.no); printf("msg2 payload: %s\n", (&msg2)->payload); return 0;}void new_message(message *msg, int no, char *str) { msg = malloc(sizeof(msg)); msg->payload = malloc(sizeof(char) * (strlen(str)+1) ); strncpy(msg->payload, str, strlen(str)); msg->no = no; printf("no in function: %d, payload in function: %s\n", msg->no, msg->payload);}void print_message(void *m) { message *msg; msg = (message *) m; printf("Thread %d owns %s\n", msg->no, msg->payload);}
The problem is the data is printed correctly within the function where values are assigned to the structure, but not in main function.
no in function: 1, payload in function: hellono in function: 2, payload in function: world!msg1 no: 1msg1 payload: ���msg2 no: 134519100����������������9�u߃�[^_]��
How can I fix this problem?Thanks