Thread: problem with pointers in strcat

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    1

    problem with pointers in strcat

    Hi everyone,
    There are some problem with the pointers in my program:
    Code:
    #include <stdlib.h>
    #include <string.h>
    
    int main(){
    	char *s1 = "Opa";
    	char *s2 = "hail!";
    	
    	strcat(s1,s2);
    	
    	printf("%s", s1);
    	
    	
    	
    	return 0;	
    }
    what can i change in my code?

    Thanks.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    make s1 space for s1 and s2, and make it not point to a string constant. If you change a string constant ("osidjidfs") then your program could crash.

    to do that, you could make s1 an array with space enough for both:
    Code:
    	char s1[20] = "Opa";
    	char *s2 = "hail!";
    http://www.cplusplus.com/reference/c...ng/strcat.html
    http://www.cprogramming.com/tutorial/c/lesson8.html
    http://www.cprogramming.com/tutorial/c/lesson9.html
    http://www.cprogramming.com/tutorial/c/lesson6.html
    Last edited by robwhit; 08-15-2007 at 11:27 PM.

  3. #3
    Day Dreamer
    Join Date
    Apr 2007
    Posts
    45
    exactly as robwhit pointed s1 does not have enough memory to store s1+s2 and hence the problem.

    Make s1 an array or allocate enough memory for s1 so that it may store the length of s1+s2.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with malloc and pointers to pointers
    By mike_g in forum C Programming
    Replies: 7
    Last Post: 03-29-2008, 06:03 PM
  2. A problem with pointers
    By vsla in forum C Programming
    Replies: 2
    Last Post: 10-10-2007, 04:14 AM
  3. STRCAT problem
    By Frusciante in forum C Programming
    Replies: 9
    Last Post: 07-04-2007, 06:15 AM
  4. pointers problem
    By toshog in forum C Programming
    Replies: 4
    Last Post: 09-11-2006, 03:17 AM
  5. Problem writing swap using pointers
    By joshdick in forum C++ Programming
    Replies: 1
    Last Post: 02-29-2004, 10:06 PM