I'm basically coding my very own string functions in C.
I've been trying to do the strcat function using pointers and cannot seem to understand whether I should be allocating memory using malloc or leaving it up to the heap.
char *my_strcat(const char *s1, const char *s2)
{
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;
    unsigned char *string;
        //string = malloc(strlen(s1) + strlen(s2) + 1);
    while (*p1 != '\0')
{
        *string = *p1;
        string++;
        p1++;
        if(*p1 == '\0')
        {
            while(*p2 != '\0')
            {
                *string = *p2;
                string++;
                p2++;
            }
        }
    }
    return (char *)string;  
}
Any tips on more efficiently performing this task or things I'm doing wrong would be great!
Cheers
EDIT
OK so I got a working solution but just wondering after I use malloc where should I free() it?
char *my_strcat(const char *s1, const char *s2)
{
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;
    char *string = malloc(sizeof(char *));
    char *res = string;
    while (*p1 != '\0')
{
        *string = *p1;
        string++;
        p1++;
    }
    while (*p2 != '\0')
    {
        *string = *p2;
        string++;
        p2++;
}
    *string = '\0'; 
    return (char *)res; 
}
Answer
First, I assume that the allocation is commented out by mistake.
- You need to save the pointer that you allocate, and return it. Otherwise, you're returning a pointer string, which points at the end of the concatenation result
- You are not terminating the resultant string; you need to add *string = '\0'
- You should move the second loop to the outside of the first loop, and drop the ifcondition around it: if the first loop has terminated, you know that*p1points to\0
char *string = malloc(strlen(s1) + strlen(s2) + 1);
char *res = string;
for (; *p1 ; *string++ = *p1++);
for (; *p2 ; *string++ = *p2++);
*string = '\0';
return res;  
 
No comments:
Post a Comment