-1

I want to do in C, what can be achieved in Java as follows

String str = "hello";
System.out.println(str + 'a');

I have written the following. 1. It doesn't work 2. Is there an easier way to do this in C, something that can be achieved in java in a single line.

#include <stdio.h>

char* charcat(char str[], char c);

int main(void)
{
 char str[] = "hello";
 printf("%s\n",charcat(str,'a'));
}

char* charcat(char str[], char c)
{
 char newstr[] = {c,'\0'};
 char temp[20];

 strcpy(temp,str);
 strcat(temp,newstr);

 return temp;
}

EDIT : I have edited based on ameyCU's response.

char* charcat(char str[], char c);

int main(void)
{
 char str[] = "hello";

 printf("%s\n",charcat(str,'a'));
}

char* charcat(char str[], char c)
{
 char* temp;
 char newstr[] = {c,'\0'};

 temp = malloc((strlen(str) + 1)* sizeof(char));
 strcpy(temp,str);
 return strcat(temp,newstr);
}

EDIT 2:

char* charcat(char str[], char c);

int main(void)
{
 char str[] = "hello";
 char temp[20];

 strcpy(temp,str);
 printf("%s\n",charcat(temp,'a'));
}

char* charcat(char str[], char c)
{
 char newstr[] = {c,'\0'};
 return strcat(str,newstr);
}
saltandwater
  • 791
  • 2
  • 9
  • 25

6 Answers6

3

I think what you were trying to do was this:

char* charcat(char str[], char c)
{
 char newstr[] = {c,'\0'};
 char *temp=(char *)malloc((strlen(str)+1+1)*sizeof(char));

 strcpy(temp,str);
 strcat(temp,newstr);

 return temp;
}

make sure you free() the pointer.

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
  • I find your answer helpful. But I have one question that is not directly related to the original post. I see that you are typecasting temp to char*, so does that convert temp from being type char to being type char*. Is this same as char* temp=malloc((strlen(str)+1+1)*sizeof(char)); – saltandwater Aug 01 '15 at 12:16
  • 1
    that is perfectly ok. It is unnecessary anyway. a Void pointer(which is returned by calloc and malloc) can be automatically and safely promoted to any other pointer type in this case. Please check this link [Do I cast the result of malloc?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Aritra Chakraborty Aug 01 '15 at 14:26
1

Problem is that you return a local variable.

return temp;

temp is local variable and its scope is just inside the function it is declared.

After concatenation -strcat(temp,newstr);

You can do this -

strcpy(str,temp);
return str;

But this will also change the contents of original array.

EDIT

To keep original array intact assign a pointer to string in function and return the pointer .

And also to use functions like strcpy and strcat you need to include string.h header.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • I do not want to do that since I don't want to change the contents of the original string I passed. Is there another way? – saltandwater Aug 01 '15 at 11:20
  • @saltandwater Yes if you want to keep original array to be intact assign a pointer to it inside function. – ameyCU Aug 01 '15 at 11:34
  • thanks for the reply. Please can you have a look at my edit above and see if it's right. Please give me feedback about the malloc line. Is that correct? – saltandwater Aug 01 '15 at 11:58
  • 1
    @saltandwater Yes that's correct `temp = malloc((strlen(str) + 2)* sizeof(char));` should do it . As you want extra character to be added and `1` for null character. And also you can `return` the pointer instead i.e `return temp;` and free it in `main`. – ameyCU Aug 01 '15 at 11:59
  • @saltandwater This is exactly what Arita Chakraborty answered .Please take a look at her answer. – ameyCU Aug 01 '15 at 12:02
  • thank you. I just have one more question. What I'm doing above, is this same as declaring a temp variable inside main, copying the contents of the original string to temp and calling the function charcat using that temp variable. Something like EDIT 2 ? – saltandwater Aug 01 '15 at 12:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/84888/discussion-between-ameycu-and-saltandwater). – ameyCU Aug 01 '15 at 12:19
1

You can use strcat() function

char  str1[20]="hello";
strcat(str1,"c");
printf("%s",str1);
Steephen
  • 14,645
  • 7
  • 40
  • 47
  • 1
    @Steephen, this is not what I'm looking for. Note that "c" is not a string. It's a character like char c = 'c'; for me. – saltandwater Aug 01 '15 at 11:22
1

This uses snprintf() to get the required length for the target string. Memory is allocated and then snprintf() creates the target string.

#include<stdio.h>
#include<stdlib.h>

char* charcat(char str[], char c);

int main ( ) {
    char str[] = "hello";
    char *output = NULL;

    printf ( "str-> %s\n\n", str);
    if ( ( output = charcat ( str, 'a'))) {//successful return of pointer
        printf ( "output-> %s\n", output);
        free ( output);//release memory
    }
    return 0;
}

char* charcat(char str[], char c)
{
    char *temp = NULL;
    int length = 0;

    length = snprintf ( NULL, 0, "%s%c", str, c);//get required length
    if ( ( temp = malloc ( length + 1))) {//allocate plus one for '\0'
        snprintf ( temp, length + 1, "%s%c", str, c);//malloc succeeds make target
    }

    return temp;
}
user3121023
  • 8,181
  • 5
  • 18
  • 16
0

It is always better to use strncat() instead of strcat to avoid buffer overflows.

#include <cstdio>
#include <cstring>

int main ()
{
  char str[20] = "hello";
  strncat (str, "a", sizeof(str) - strlen(str) - 1);
  printf("%s",str);
  return 0;
}

Output:

helloa
RUN SUCCESSFUL (total time: 49ms)
Anoop Toffy
  • 918
  • 1
  • 9
  • 22
  • Also refer [http://stackoverflow.com/questions/6903997/how-can-i-use-strncat-without-buffer-overflow-concerns] – Anoop Toffy Aug 01 '15 at 11:13
  • Hmmm, This answer recommends " strncat() instead of strcat to avoid buffer overflows" yet then does `sizeof(str) - strlen(str) - 1` which can easily underflow unsigned arithmetic. – chux - Reinstate Monica Aug 01 '15 at 19:01
0

Something like Java in a single line

// String str = "hello";
// System.out.println(str + 'a');

const char *str = "hello";
printf("%s%c\n", str, 'a');

Or is one wants to print a concatenated string, we need to do memory management.

char *charcatconst char *src, int ch) {
  size_t len = strlen(src);
  char *s = memcpy(malloc(len+2), src, len);  // Out-of-memory check omitted.
  s[len] = ch;
  s[len+1] = '\0';
  return s;
} 

// simple usage, but a memory leak
puts(charcat("hello", 'a'));

// Better to free memory explicitly
char *s = charcat("hello", 'a');
puts(s);
free(s);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256