0

I'm trying to convert a character into a string, but if I do it this way ...

 char* Make_String(char ch)
 {
   char *d = " "; //(char*)malloc(2*sizeof(char));
   d[0] = ch;
   d[1] = '\0';

   return d;
 }

... then the output doesn't contain the characters I expect it to. On the other hand, if I allocate memory dynamically via malloc (as shown in commented part after //) then it works fine. Please explain why this is happening.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 2
    You must not modify string literals. – MikeCAT Aug 22 '20 at 15:28
  • OK. Noted . But how does that selectively avoids printing the operands in the final result. – Ravikant Sharma Aug 22 '20 at 15:31
  • 2
    By giving your program undefined behavior. Anything within the power of your C implementation to do could happen. The language provides no basis for explaining the specific behavior you observe. At a guess, however, what might be happening in this case is that the single-space string literal you are attempting to modify simply isn't modified. – John Bollinger Aug 22 '20 at 15:36
  • Duplicate of https://stackoverflow.com/questions/7480597/why-cant-i-edit-a-char-in-a-char – Daniel Widdis Aug 24 '20 at 14:54

2 Answers2

1

String literals should not be changed. Attempting to do so invokes Undefined Behavior.

When using a pointer to string literal you should use const i.e. const char *d = " "; this way if in your code you try to change the string literal you'll get a compilation error and avoid introducing UB in your program.

If you want a string that can be changed you use char d[] = " ";. This copies the string literal into your char array, so you can change at will.

If you want to return the string from within the function then you need to use the malloc method you used or use a static char array static char d[] = " ";

When using malloc don't forget to free the memory after you use it.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
1

d[0] = ch; attempts to change the contents of a string literal, which is undefined behavior (UB).

char *d = " ";
d[0] = ch;  // UB

Allocation works as the memory is alterable.

char *d = malloc(2*sizeof(char));
d[0] = ch; // OK

An alternative to Make_String(char ch) is a string literal. Example: to converts a char into its hexadecimal value.

char hex_char = 'b';
char *s = (char [2]){ hex_char }; // string literal: initializes with 'b', '\0'
int val = (int) strtol(s, 0, 16);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256