Thread: concatenating two strings

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    5

    concatenating two strings

    Hi,
    I am new to c. I was trying to print out this message using pointers.

    This is a test
    No - it is not a test

    This is my code.

    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    int main(){
       char *p = "This is a test";
       printf("%s\n",p);
       strcat(p,"No - this is a test");
       printf("%s\n",p);
    }
    Your help will be appreciated.

  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    not sure, but I think when you use char *p = "hi"; that you make a constant, you can't alter it because the compiler allocated space only for those character, I think...

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by chrismiceli
    not sure, but I think when you use char *p = "hi"; that you make a constant, you can't alter it because the compiler allocated space only for those character, I think...
    Correct. They're using string literals, and as such, you cannot (read: shouldn't try to) modify them.

    You'll probably want an array for the first sentence, long enough to hold them both. Either that or do it dynamicly. But an array should suffice for this.

    However, if your code actually did work, you would end up with this output:
    This is a test
    This is a testNo - this is a test
    strcat adds one string to the end of another. It doesn't replace the first string with the second.

    If you really want the first string overwritten, you'd need to use strcpy (or strncpy) or something similar.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Easier way of concatenating a lot of strings?
    By Evenstevens in forum C Programming
    Replies: 2
    Last Post: 05-09-2009, 01:29 PM
  2. concatenating strings?
    By liri in forum C Programming
    Replies: 11
    Last Post: 08-24-2007, 05:34 PM
  3. Concatenating 2 strings
    By AngKar in forum C Programming
    Replies: 14
    Last Post: 04-25-2006, 10:51 AM
  4. concatenating more than 2 strings
    By Grunt12 in forum C Programming
    Replies: 3
    Last Post: 11-25-2005, 05:31 PM
  5. Concatenating strings (dynamic array using pointers)
    By Tankndozer in forum C Programming
    Replies: 8
    Last Post: 07-01-2004, 07:27 AM