Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is another alternative to strcat and strncat functions in C?

This is the specific section of code where I am facing issues using both strcat() and strncat() functions to concatenate two strings.

The strcat() function is declared as char *strcat(char *dest, const char *src) and strncat() as char *strncat(char *dest, const char *src, size_t n), however both of them give issues when the second parameter is a single character from string, i.e., which does not end with '\0'. I need to concatenate the a character to a string.

So is there any alternative to these two functions or is there any way to make these functions work for me?

    char *cipher_str = (char *)malloc(sizeof(char) * 26);
    for (int j = 0; j < col; j++) {
        for (int i = 0; i < col; i++) {
            if (min == cipher[0][i] && (done[i] != 1)) {
                done[i] = 1;
                for (int k = 0; k < rows; k++)
                    strcat(cipher_str, cipher[i][k]);
                }
            }
            ...
like image 857
Nishit Mengar Avatar asked Sep 02 '25 05:09

Nishit Mengar


2 Answers

Th easiest way here is just to append the character "manually" to the string, for example:

    int m=0;

    ....
        cipher_str[m++]=cipher[i][k];
    ....
    cipher_str[m]='\0';
like image 173
Paul Ogilvie Avatar answered Sep 04 '25 20:09

Paul Ogilvie


Since you are using strcat to append 1 character, you can use this function.

void strcat(char* dest, char src)
{
    int size;
    for(size=0;dest[size]!='\0';++size);
    dest[size]=src;
    dest[size+1]='\0';
}

And you mentioned that you have '\0' at end of your 'cipher_str', i used it to determine length.

like image 44
svtag Avatar answered Sep 04 '25 20:09

svtag