Q:

problem with char arrays in network programming

I have the following:
nodeID = abcde.abc.edu_12345
and I need to append the an underscore and a 10digit value returned by time() to create the following:
node_inst_ID = abcde.abc.edu_12345_1016320007
where 1016320007 is the 10 digit value returned by time(). I am trying the following code but it doesnt seem to work:
#define NODE_ID_LENGTH 20
#define NODE_INST_ID 31
char nodeID[NODE_ID_LENGTH]
char node_inst_ID[NODE_INST_ID];
int main()
{
    /*
    Building of nodeID is a bit complex. So its hard to put all the code here. But printing the following at this point gives this
          for(int i = 0; i < NODE_ID_LENGTH; i++)
            {
              printf("%c", nodeID[i]);
            }
    gives
    abcde.abc.edu_12345
    If you need to know any more info about nodeID, I can post the print out of things that you suggest. 
    */

    long int seconds = time(NULL);
    char buf[10];
    sprintf(buf, "%ld", seconds);
    snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
    node_inst_ID[20] = '_';
    node_inst_ID[21] = '\0';
    cout<<"Node instance ID = "<<node_inst_ID<<endl;

    /* 
    I havent yet added the code for appending the time stamp. But I am expecting a print out for the above code like this:
    Node instance ID = abcde.abc.edu_12345_
    But the code is printing only
    Node instance ID = abcde.abc.edu_12345
    It is not adding the underscore at the end. 
    */
}

Can anyone point out what the mistake is? Thanks in advance. 

A:

snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
node_inst_ID[20] = '_';
node_inst_ID[21] = '\0';

This assumes that the string is exactly 20 characters long - it isn't. Try this:
snprintf(&node_inst_ID[0], 20, "%s", &nodeID[0]);
strcat(node_inst_ID, "_"); // strcat is safe in this context, usually you should use strncat.

EDIT: If you want to still use snprintf, the easy way is:
int len = strlen(node_inst_ID);
snprintf(node_inst_ID + len, sizeof(node_inst_ID) - len, "%whatever", the, args);

