Search code examples
cpointersconcatenation

C Pointers Problem Concatenating Strings


I am going through some exercises and am trying to concatenate two strings using only pointers (no char arrays). My code seems to compile(Note: I am using the old 16-bit Open Watcom compiler):

#include <stdio.h>

int main(){
  char *str1 = "first";
  char *str2 =" second";

  strcat2(str1,str2);

  for(;*str1!='\0';str1++){
      printf(str1);
  }

  return 0;
}

int strcat2(char *s,char *t){
  for(;*s!='\0';s++){
    ;
  }

  while((*s++ = *t++)!='\0'){
    ;
  }

  *t++;
  t='\0';

  return 0;
}

When I tried to run it nothing happens. I am sure my above work is horribly flawed. Any advice and help will be much appreciated.


Solution

  • the str1 and str2 you have declared are string literals, which cannot be modified. In linux executables the contents of the address which the str1 and str2 points to are stored in .rodata section of the executable which is not writeable. In other executables the contents are stored in a similar location which is not writeable. You should use an array or dynamically allocated memory area to do this work. Make sure when concatenating the string to which you are pasting the other string has enough space to hold both of them.

    EDIT1:

    Either do

    char str1[BUFF_SIZ] = "Hello", str2[BUFF_SIZ] = " Man";
    /* Now do strcat */ 
    /* The strlen (str1) + strlen (str2) should be lessthan BUFF_SIZ */
    

    or

    char *str1, *str2;
    str1 = malloc (sizeof (char) * BUFF_SIZ);
    str2 = malloc (sizeof (char) * BUFF_SIZ);
    strcpy (str1, "Hello");
    strcpy (str2, " Man");
    /* Now do strcat */ 
    /* The strlen (str1) + strlen (str2) should be lessthan BUFF_SIZ */