Thread: question about strcat() in C

  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
    Chappell Hill, Texas
    Posts
    2,332
    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.
    Mainframe assembler programmer by trade. C coder when I can.

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, 12:59 PM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09: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