I am experienced in Java but I am very new to C. I am writing this on Ubuntu.
Say I have:
char *msg1[1028];
pid_t cpid;
cpid = fork();
msg1[1] = " is the child's process id.";
How can I concatenate msg1[1] in such a way that when I call:
printf("Message: %s", msg1[1]);
The process id will be displayed in front of ” is the child’s process id.”?
I want to store the whole string in msg1[1]. My ultimate goal isn’t just to print it.
Easy solution:
Not so easy, but also not too complicated solution: use the (non-portable)
asprintffunction:If your platform doesn’t have
asprintf, you can usesnprintf:or define
asprintfin terms ofsnprintf. It’s not very hard, but you have to understand varargs.asprintfis very useful to have and it should have been in the C standard library ages ago.EDIT: I originally advised casting to
long, but this isn’t correct since POSIX doesn’t guarantee that apid_tvalue fits in along. Use anintmax_tinstead (include<stdint.h>to get access to that type).