Something Loopy in Assigning Strings

MattFunke's Avatar
Newbie Member
I tried this in desperation after strcat() refused to work. I just want to concatenate three strings. Can anyone tell me why this doesn't work? I can see the creation of "10", but not of "11", though there's plenty of room on the disk for both. Moreover, if I ask for a printf of fieldn and strlen(fieldn) for all three fields, I get the right responses. field1[] is more than long enough to handle the job.

Code:
void AssembleData(char field1[], char field2[], char field3[])
{
    int i;
    int startPos;
    int stopPos;

    if (field2[0] != '\0')
    {
        startPos = strlen(field1);
        stopPos = startPos + strlen(field2);

        system("touch /var/log/10\n");

        for (i = startPos; i < stopPos; i++)
        {
            field1[i] = field2[i - startPos];
        }

        system("touch /var/log/11\n");

        if (field3[0] != '\0')
        {
            startPos += strlen(field2);
            stopPos += strlen(field3);

            for (i = startPos; i < stopPos; i++)
            {
                field1[i] = field2[i - startPos];
            }
        }
    }
}
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
That's just silly. Disk operations are orders of magnitude slower than memory operations. Use strcat or strncat. They work. If you can't get them to work, show THAT code not this grossly over-footprint, underperforming stuff.
0
MattFunke's Avatar
Newbie Member
I explained in the first message that I tried strcat() and that it doesn't work, either. Here's the code. As usual, I can get "10" but not "11".

Code:
void AssembleData(char field1[], char field2[], char field3[])
{
    system("touch /var/log/10\n");

    field1 = strcat(field1, field2);
    field1 = strcat(field1, field3);

    system("touch /var/log/11\n");
}
I would appreciate any help you could lend, but I would also appreciate it if you could acknowledge the things that I've already mentioned I've tried without success.
0
MattFunke's Avatar
Newbie Member
Found it! Here's the problem. This is what I was doing, essentially:

Code:
#define HI_THERE "hi "
#define ID10T "idiot"
char *data;

data = strcat(HI_THERE, ID10T);
... and the statement, of course, after the preprocessor was done with it, looked like this:

Code:
data = strcat("hi ", "idiot");
It was trying to concatenate literals, not string variables. This works:

Code:
char data[80] = HI_THERE;
char data2[80] = ID10T;

data = strcat(data, data2);
<dope slaps self>
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Actually, the second string can be a literal. There MUST be enough storage in the destination string to accomodate the original plus the second string (literal or otherwise).