2

I'm currently doing the pest, and I'm at the step which I have "to define a string called path that contains the concatenation of root (a global variable) and absolute-path."

As suggested, I'm using the strcat function. The code compiles nicely but strcat doesn't return a valide value.

Here's my code:

        char croot[50], apath[50];

        strcpy(croot, "/home/jhavard/Dropbox/CS50/pset6/pset6/public");
        strcpy(apath, url);

        char tmp = *strcat(croot, apath);

        char path[] = {tmp};
        printf("%s\n", path); // for debug 

What am I doing wrong?

2

You don't have to predeclare the length of croot and apath, and then copy the values in there. That way you spend away valuable space in memory. Also your use of the strcat() function is wrong. Here is a correct version of your program:

char final[50] = {0};
char croot[] = "/home/jhavard/Dropbox/CS50/pset6/pset6/public/";
char apath[] = "thisIsThePath";
strcat(final, croot);
strcat(final, apath);
printf("%s\n", final);

With output:

/home/jhavard/Dropbox/CS50/pset6/pset6/public/thisIsThePath

In your code just replace "thisIsThePath" of my code with url and it should do the trick.


EDIT
Even better you could do this:

char croot[] = "/home/jhavard/Dropbox/CS50/pset6/pset6/public/";
char apath[] = "thisIsThePath";

int len = strlen(croot) + strlen(apath) + 1;
char* final = calloc(1, len * sizeof(char));

strcat(final, croot);
strcat(final, apath);
printf("%s\n", final);
free(final);
  • It works! Thanks a lot. I didn't correctly understood the man page of strcat :) – Edouard Jamin Jul 20 '15 at 19:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .