I'm trying to write a string concatenating in C. I'm not allowed to use strcat. My program compiles without errors. But when I run it, I get a segfault. Can someone tell me what's wrong? Thanks. Here's my code
char* concat(char** strs, unsigned int nstrs)
{
unsigned int outlen = 0;
char* output;
int x;
int y;
for(x = 0; x < nstrs ; x++) {
outlen += strlen(strs[x]);
}
output = (char *) malloc(outlen * sizeof(char));
for(x = 0; x < nstrs ; x++) {
for(y = 0 ; y < strlen(strs[x]) ; y++) {
output[x+y] = strs[x][y];
}
}
return output;
}
int main(int argc, char *argv[])
{
int strsize = 0;
int x;
for(x = 0; x < argc; x++) {
strsize += strlen(argv[x+1]);
}
char** strs;
strs = (char* *) malloc(sizeof(char)*strsize);
for(x = 0; x < argc; x++) {
strs[x] = argv[x+1];
}
concat(strs, (argc - 1));
printf("%s", concat(strs, (argc -1)));
free(strs);
return 0;
}