Thread: strcat(), wrong output!

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    71

    strcat(), wrong output!

    i write this:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main() 
    {
    	char s[15];
    	strcat(s,"abcde");
    	fputs(s,stdout);
    	getch();
    	return 0;
    
    }
    and the output is:
    Image

    Where did I go wrong?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    s[15] is created on the program's stack (because it's inside a function)... thus it's content is not reset to nulls and when you do strcat you also get whatever junk is in the stack at the address of the array...

    Try it like this:
    Code:
    char s[15] = {0};
    strcat(s,"abcde");
    In practical aps you have two choices... a) use strcpy() the first time then strcat() after or b) clear the memory to 0 as I showed you.

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    71
    ok,tanks
    I use point b)


    L.E: in this exemple why the output is correct???

  4. #4
    'Allo, 'Allo, Allo
    Join Date
    Apr 2008
    Posts
    639
    Quote Originally Posted by nutzu2010 View Post
    L.E: in this exemple why the output is correct???
    Quote Originally Posted by CommonTater
    a) use strcpy() the first time then strcat() after
    What he said

  5. #5
    Registered User
    Join Date
    Dec 2010
    Posts
    71
    sorry,now I see
    first is use strcpy()

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by nutzu2010 View Post
    ok,tanks
    I use point b)


    L.E: in this exemple why the output is correct???
    If you go look at the example you will see that he (correctly) used strcpy() the first time then strcat() after.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 12-08-2010, 04:36 PM
  2. Wrong Output!
    By kolliash in forum C++ Programming
    Replies: 6
    Last Post: 06-19-2008, 07:55 AM
  3. Getting wrong output from a class
    By orikon in forum C++ Programming
    Replies: 11
    Last Post: 11-18-2005, 07:58 PM
  4. Why is the output of this wrong?
    By Tokimasa in forum C++ Programming
    Replies: 4
    Last Post: 11-30-2004, 01:58 PM
  5. Leap year program prints wrong output
    By Guti14 in forum C Programming
    Replies: 8
    Last Post: 08-24-2004, 11:56 AM