Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C char to string (passing char to strcat())

my problem is in convert a char to string i have to pass to strcat() a char to append to a string, how can i do? thanks!

#include <stdio.h>
#include <string.h>

char *asd(char* in, char *out){
    while(*in){
        strcat(out, *in); // <-- err arg 2 makes pointer from integer without a cast
        *in++;
    }
    return out;
}

int main(){
    char st[] = "text";
    char ok[200];
    asd(st, ok);
    printf("%s", ok);
    return 0;
}
like image 440
frx08 Avatar asked Feb 27 '10 13:02

frx08


2 Answers

Since ok is pointing to an uninitialized array of characters, it'll all be garbage values, so where the concatenation (by strcat) will start is unknown. Also strcat takes a C-string (i.e. an array of characters which is terminated by a '\0' character). Giving char a[200] = "" will give you a[0] = '\0', then a[1] to a[199] set to 0.

Edit: (added the corrected version of the code)

#include <stdio.h>
#include <string.h>

char *asd(char* in, char *out)
{

/*
    It is incorrect to pass `*in` since it'll give only the character pointed to 
    by `in`; passing `in` will give the starting address of the array to strcat
 */

    strcat(out, in);
    return out;
}

int main(){
    char st[] = "text";
    char ok[200] = "somevalue"; /* 's', 'o', 'm', 'e', 'v', 'a', 'l', 'u', 'e', '\0' */
    asd(st, ok);
    printf("%s", ok);
    return 0;
}
like image 195
legends2k Avatar answered Nov 06 '22 10:11

legends2k


strcat will not append single characters. Instead it takes a const char* (a full C-style string) which is appended to the string in the first parameter. So your function should read something like:

char *asd(char* in, char *out)
{
    char *end = out + strlen(out);

    do
    {
        *end++ = *in;

    } while(*in++);

    return out;
}

The do-while loop will include the zero-terminator which is necessary at the end of C-style strings. Make sure that your out string is initialized with a zero-terminator at the end or this example will fail.

And as an aside: Think about what *in++; does. It will increment in and dereference it, which is the very same as in++, so the * is useless.

like image 3
AndiDog Avatar answered Nov 06 '22 11:11

AndiDog