question about strcat() in C

This is a discussion on question about strcat() in C within the C Programming forums, part of the General Programming Boards category; Code: int main() { char* date1="Dec 29, 8:30"; char* date2="Dec 28, 7:30"; char* year =" 2009"; strcat(date1,year); strcat(date2,year); return 0; ...

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    41

    Post question about strcat() in C

    Code:
    int main()
    {
       
       char* date1="Dec 29, 8:30";
       char* date2="Dec 28, 7:30";
       char* year =" 2009";
       strcat(date1,year);      
       strcat(date2,year);
       return 0;
    }
    After compiling and executing, the compiler gives an error
    Code:
    red 312 % time.out
    Segmentation fault
    After looking at the function strcat(), it takes 2 args of type of pointer and it is what i am passing to strcat(). I dont know i got the error. I need a explanation for it.
    Thanks

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    35
    strcat adds on the second string to the end first string. so you have to leave some space at the end of the first string. for example

    Code:
       char date1[20]="Dec 29, 8:30";
       char date2[20]="Dec 28, 7:30";
       char* year =" 2009";
       strcat(date1,year);
       strcat(date2,year);
       printf("%s\n%s\n", date1, date2);
    date1 is an array that has a bit of room left over at the end. same with date2. so you can use strcat now since there is room to add year on the end

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Also, when declaring strings like that, your compiler may mark those strings to be placed into read-only memory when the program is loaded, and thus adding more room to them to do a strcat() later might be a fruitless effort.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An interesting question about strcat
    By meili100 in forum C++ Programming
    Replies: 3
    Last Post: 07-07-2009, 01:59 PM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 01:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 10:47 PM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21