开发者

C Pointers Problem Concatenating Strings

开发者 https://www.devze.com 2023-03-09 03:06 出处:网络
I am going through some exercises and am tr开发者_如何学JAVAying to concatenate two strings using only pointers (no char arrays).

I am going through some exercises and am tr开发者_如何学JAVAying 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.


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 */


Your code won't work. To be pedantic it invokes undefined behaviour because you are trying to modify the content of a string literal.

char *str1 = "first";
char *str2 =" second";

str1 points to "first" which resides in const memory location.

Instead to having a pointer to the string literal you should have an array of characters with sufficient capacity so as to hold the concatenated string "firstsecond"

This works as per expectation

#include <stdio.h>
int strcat2(char *s,char *t){    
   for(;*s!='\0';s++){
   }
   while((*s++ = *t++)!='\0'){        
   }
   t='\0';
   return 0;
}
int main(){
  char str1[15] = "first";
  char *str2 =" second";

  strcat2(str1,str2);
  printf("%s",str1);
  return 0;
}   

Online demo here


quote from man:strcat:

  char * strcat ( char * destination, const char * source );
  ...
  Parameters
  destination
  Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

Your destination string is not large enough.


You need a writable and large enough buffer to write to, like this

char str1[32] = "first";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号