I am having some problems when returning with printf of a char array from a struct in C.
struct q_entry
{
long mtype;
char mtext[MAXLENGTH + 1];
};
The long mtype from the struct is returning fine, but the string is just returning some weird characters.
int proc_obj(struct q_entry *msg)
{
printf("\npriority: %ld name: %s\n", msg->mtype, msg->mtext);
}
It just returns some strange characters like "priority: 1 name: ▒▒(" and not "priority: 1 name: hello"
I am populating the struct using the following code
int enter(char *objname, int priority)
{
...
strncpy(s_entry.mtext, objname, sizeof(s_entry.mtext) - 1);
s_entry.mtype = priority;
// Send the message
if (msgsnd(s_qid, &s_entry, len, 0) == -1)
{
printf("error: msgsnd failed\n");
return(-1);
}
else
{
return(0);
}
}
I don't have much experience with C, so I don't know too much about using structs. Please let me know if more context or parts of the code is needed. Any kind of help would be very helpful.
I have added a little more code in enter above, and here is more code of the when enter and proc_obj are called
main(int argc, char **argv)
{
int priority;
if (argc != 3)
{
printf("error: incorrect number of arguments\n");
exit(1);
}
else
{
priority = atoi(argv[2]);
}
if (enter(argv[1], priority) < 0)
{
printf("error: message entering failed\n");
exit(1);
}
exit(0);
}
This is in a different file from enter and above code
int server(void)
{
int mlen, r_qid;
struct q_entry r_entry;
// Initialize queue
if ((r_qid = init_queue()) == -1)
return(-1);
for (;;)
{
if ((mlen = msgrcv(r_qid, &r_entry, MAXLENGTH, (-1 * MAXPRIOR), MSG_NOERROR)) == -1)
{
printf("error: msgrcv failed\n");
exit(1);
}
else
{
proc_obj(&r_entry);
}
}
}