Click to See Complete Forum and Search --> : a strcat question
bsamuels
10-13-2003, 08:49 PM
I am trying to concatenate 3 strings and try the simpl approach:
char * make_dir_path(char *,char *)
{
pathname = strcat(pathname,"/");
pathname = strcat(pathname,newdir);
return pathname;
}
but the output is just the first strcat: How come?
sploo22
10-13-2003, 09:15 PM
The code you posted doesn't look like it would even compile. Could you please post the exact code you were using?
EDIT: Also, the "pathname =" part is unnecessary - strcat modifies the strings in place.
bsamuels
10-13-2003, 10:17 PM
char * make_dir_path(char *pathname ,char * newdir)
{
strcat(pathname,"/");
strcat(pathname,newdir);
return pathname;
}
This compiles
Stuka
10-14-2003, 09:56 AM
It may compile, but good luck running it - ESPECIALLY if newdir is a long string. strcat modifies the passed in arguments IN PLACE - if you have only allocated enough space for the pathname variable, then using strcat() to tack newdir on the end is all but guaranteed to trample all over your memory. Your best bet would be something like this:char * make_dir_path(char *pathname, char *newdir){
char * dirpath;
int length = strlen(pathname);
length += strlen(newdir) + 2;
dirpath = malloc(sizeof(char) * length);
strcpy(dirpath, pathname);
strcat(dirpath, "/");
strcat(dirpath, newdir);
return dirpath;
} Of course, you MUST document the fact that the user of this function is required to free() the pointer returned, unless you like memory leaks.