0

I am trying to concatenate 2 character arrays but when I try it does not work and my o/p console hangs and does not print anything.

   char *str[2];
   str[0] = "Hello ";
   str[1] = "World";
   strcat(str[0],str[1]);
   printf("%s\n",str[0]);

I even tried the below code which fails as well

   char *str1 = "Hello ";
   char *str2 = "World";
   strcat(str1,str2);
   printf("%s\n",str1);

Can someone explain this?

TIA.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sandywho
  • 353
  • 1
  • 7
  • 16
  • 1
    `char *str[2]` is an array of pointers to read-only memory, swith to `str[2][50]` where 50 is the max-length of the strings, also use `strcpy` instead of `=` – David Ranieri Jun 18 '19 at 06:46
  • 1
    Quoted strings, when used to initialize pointers (as opposed to arrays), are sharable, read-only values. You cannot modify them. If you want to make changes to a string, then it needs to either be a (non-constant) array or dynamically allocated memory. – Tom Karzes Jun 18 '19 at 06:47
  • 1
    Possible duplicate of [Modifying C string constants?](https://stackoverflow.com/questions/480555/modifying-c-string-constants) – J...S Jun 18 '19 at 06:48
  • C string literals are immutable. – J...S Jun 18 '19 at 06:49

2 Answers2

0

To concatenate two strings you either have to create a new one large enough tp contain the both source strings or the one of the strings shall be large enough to hold the second appended string.

Take into account that string literals are immutable in C (and C++). Any attempt to change a string literal results in undefined behaviour.

You could concatenate strings if one of them was stored in a character array.

For example

char str1[12] = "Hello ";
const char *str2 = "World";

strcat( str1, str2 );
puts( str1 );

Or you could create a third string.

const char *str[2];
str[0] = "Hello ";
str[1] = "World";

char *str1 = malloc( strlen( str[0] ) + strlen( str[1] ) + 1 );

strcpy( str1, str[0] );
strcat( str1, str[1] );

puts( str1 );

free( str1 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

This code illustrates the problem:

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

int main(void)
{
    char *str1 = "Hello ";
    char *str2 = "World";
    char *ptr1, *ptr2;

    printf("Find the end of str1...\n");
    ptr1 = str1;
    while (ptr1[0] != '\0') {
        ptr1++;
    }
    printf("Copy str2 to the end of str1...\n");
    ptr2 = str2;
    while (ptr2[0] != '\0') {
        printf("Attempt to write to read-only memory...\n");
        ptr1[0] = ptr2[0];
        printf("We never get here.\n");
        ptr1++;
        ptr2++;
    }
    ptr2[0] = '\0';
    printf("Done.\n");
    return 0;
}

Output

Find the end of str1...
Copy str2 to the end of str1...
Attempt to write to read-only memory...
Bus error: 10