C Pointers Problem String Concatenation

I am doing some exercises and trying to combine two lines using only pointers (without char arrays). My code seems to be compiling (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 start, nothing happens. I am sure that my work above is terribly wrong. Any advice and help would be greatly appreciated.

+4
source share
4 answers

str1 and str2 that you specified are string literals that cannot be changed. In linux executables, the contents of the address pointed to by the str1 and str2 tags are stored in the .rodata section of the executable, which cannot be written. In other executable files, the contents are stored in a similar place that cannot be written. To do this, you must use an array or dynamically allocated memory area. Make sure that when you concatenate a string into which you insert another string, there is enough space to store them.

EDIT1:

Or 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); str1 = malloc (sizeof (char) * BUFF_SIZ); strcpy (str1, "Hello"); strcpy (str1, " Man"); /* Now do strcat */ /* The strlen (str1) + strlen (str2) should be lessthan BUFF_SIZ */ 
+4
source

Your code will not work. To be pedantic, it invokes undefined behavior because you are trying to modify the contents of a string literal.

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

str1 points to the "first" that is in the location of read-only memory.

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

It works as expected

 #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; } 

Demo here

+1
source

quote from a person: 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 .

0
source

For recording, a sufficiently rewritable and sufficiently large buffer is required, for example

 char str1[32] = "first"; 
0
source

All Articles