zeudarius zeudarius - 1 year ago 62
C Question

Concatenate arguments using strcpy

I want to concatenate all my arguments into a char pointer using strcpy. I'm doing this but my output is only a space.

I'm using 3 variables: 'concat' ( which should be my output ) , 'size' to get the length of all the arguments and 'kar' which is my iterator for arguments.

#include<stdio.h>
#include<string.h>
int main(int argc, char **argv)
{
int kar;
int size;
char *concat;

kar = 1;
size = 0;
//find size to malloc concat
while (kar < argc)
{
size = size + strlen(argv[kar]);
kar++;
}
//malloc size + argc for space characters
concat = malloc(size + argc);
kar = 1;
while (kar < argc)
{
strcpy(concat,argv[kar]);
strcpy(concat," ");
kar++;
}
printf("%s",concat);
}

Answer Source

strcpy() copies a string, as implied by the name. So each time you call it, you overwrite your existing string. You are looking for strcat(), which concatenates by searching the first 0 byte in the destination and copying there.

You can just replace strcpy() by strcat() in your code if you initialize concat[0] = 0; first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download