How to clear a string for the previous value after using strcat()?

Asked

Viewed 27 times

-1

I’m using the function strcat() to concatenate string and I’m having trouble returning the string to the previous state, what I’ve tried so far is this, but with nothing successful:

const char *get_route(const char *route)
{
    const char *final_str = strcat("https://discord.com/api/v9", route);
    return final_str;
}

I take the string that comes in the parameter route, as an example /users/@me and concateno with the discord_api_url, take for example https://discord.com/api/v9/users/@me, but when I use the function again, the new value that comes from route is not concatenated with the variable discord_api_url and yes with the previous one that was https://discord.com/api/v9/users/@me, I’ve tried to use malloc() in a new string and copy the https://discord.com/api/v9 for her, but when I give a free() the string goes away :p

How do I after concatenation, the URL string is not modified and I can reuse this function again?

1 answer

-1


I managed to find the following solution to work as I wanted:

char *discord_api_mutable = NULL;

const char *get_route(const char *route)
{
    static const char *discord_api_url = "https://discord.com/api/v9";
    const size_t str_size = strlen(discord_api_url) + strlen(route) + 1;

    if (discord_api_mutable == NULL)
        discord_api_mutable = malloc(str_size);
    else
        discord_api_mutable = realloc(discord_api_mutable, str_size);

    strcpy(discord_api_mutable, discord_api_url);
    strcat(discord_api_mutable, route);

    return discord_api_mutable;
}

I don’t know if it’s the right one, but it works, if anyone knows a better one, I’d be grateful

Browser other questions tagged

You are not signed in. Login or sign up in order to post.