Song Zhibo
Song Zhibo

Reputation: 39

why I can't combine the two string together?

 char* key;

 key=(char*)malloc(100);

 memset(key,'\0',100*sizeof(char));
 char*  skey="844607587";

 char* mess="hello world";


 sprintf(key,skey);

 sprintf(key,mess);
 printf("%s",key);
 free(key);

why does the printout only have the "mess" don't have skey? is there any other way to combine two strings using C?

Upvotes: 0

Views: 145

Answers (7)

anonymous
anonymous

Reputation: 151

the code is as below:

strncpy(key, skey, strlen(skey));
strcat(key, mess);

Upvotes: 0

user694733
user694733

Reputation: 16043

In addition to missing format string there were also some other problems:

char* key;
key = malloc(100); // Don't cast return value of malloc in C
// Always check if malloc fails
if(key) {
    memset(key, '\0' , 100 * sizeof(char));
    const char * skey = "844607587"; // Use const with constant strings
    const char * mess = "hello world";
    // sprintf requires format string like printf
    // Use snprintf instead of sprintf to prevent buffer overruns
    snprintf(key, 100, "%s%s", skey, mess); 
    printf("%s", key);
    free(key);
}

Edit:

Version with calloc would replace malloc and remove memset:

key = calloc(100, sizeof(char));
if(key) {
    const char * skey = "844607587";

Upvotes: 1

Riskhan
Riskhan

Reputation: 4470

your code is follows

sprintf(key,skey);
sprintf(key,mess);
printf("%s",key);

result will be "hello world"

you may change code to as follows

sprintf(key, "%s%s", skey, key);
printf("%s",key);

the result as follows "844607587hello world"

Upvotes: 0

sukhvir
sukhvir

Reputation: 5565

sprintf(key,"%s%s",skey,mess);

for adding them separately :

sprintf(key,"%s",skey);
strcat(key, mess);

Upvotes: 3

rockstar
rockstar

Reputation: 3538

printf("Contcatened string = %s",strcat(skey,mess));

Upvotes: 1

Rafi Kamal
Rafi Kamal

Reputation: 4600

sprintf(key,skey);

It writes skey to key.

sprintf(key,mess);

It writes mess to key, overwriting previously written skey.

So you should use this:

sprintf(key,"%s%s", skey, mess);

Upvotes: 1

mvp
mvp

Reputation: 116197

You are using sprintf twice on the same buffer, so it gets overwritten.

You could use strcat like this:

strcpy(key, skey);
strcat(key, mess);

Upvotes: 1

Related Questions