What is wrong with the following c prog??char *s1 = "hello";char *s2 = "world";char *s3 = strcat(s1, s2);Please provide me explainations??

Showing Answers 1 - 9 of 9 Answers

nitdgp

  • Jun 19th, 2006
 

Since what is present in memory beyond "United" is not known and we  are attching "Front" at the end of "United", thereby overwriting something, which is an unsafe thing to do.

  Was this answer useful?  Yes

ratheesh.n

  • Jul 18th, 2006
 

there is no problem in initialising a char pointer in its declaration.

so we can write char *s1="hello";

and char *s2="word";

but when we concatenate two strings in to a third one,then we must assign memory to the third pointer before the assignment as

char *s3=(char*)malloc(sizeof(char)*(strlen(s1)+strlen(s2)));

*s3=strcat(s1,s2);

  Was this answer useful?  Yes

pranav

  • Jul 24th, 2006
 

the above code is perfectly fine....and there is no need of allocating memory for it

  Was this answer useful?  Yes

shaanxxx

  • Aug 20th, 2006
 

lets read what is strcat :)strcat() concatenate two strings SYNOPSIS#include char *strcat(char *s1, const char *s2); DESCRIPTIONThe strcat() function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. If copying occurs between objects that overlap, the behavior is undefined. "The function strcat() does not allocate any storage. The caller must insure that the buffer pointed to by s1 is long enough for string s2 and its terminating null character. PARAMETERS"s1 Is the null-terminated string to be modified. s2 Is the null-terminated string to be copied to the end of s1. RETURN VALUESThe strcat() function returns the value of s1.my comment :It mean that S1 should have enough memory to s2. But here we didnt allocate memory for S1 since it is constant array of charachter . You cant go and write beyond that array. above programme will work in turbo C and it will not VC++ and linux

arthur

  • Sep 5th, 2006
 

two things wrong

1.s1 is const string and can't be changed

2.strcat does not returnes value,it is void

  Was this answer useful?  Yes

UMESH RAM

  • Sep 7th, 2006
 

HI  ARTHUR  ,  i m agree with ur ans.

strcat doesn't return  any char datatype

and constant string cant change its value.

  Was this answer useful?  Yes

dasam

  • Mar 31st, 2007
 

Friends, the return value of strcat is not void, it is char*. please see the below line ..char * strcat(char * s1, const char * s2);Thanks :)

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions