• C

explanation for the following code?

actually str will have address of abc, str1 will have address of ABC,
hope my view is correct?

while concatinating how it performs ?
and gives output as abcABC

i want to know whether value of both pointers are concatinated?
i am having doubt here!!!

char *str="abc";
char *str1="ABC";
char *str2;

Open in new window

Who is Participating?
mnhConnect With a Mentor Commented:
strcat concatenates the contents of str1 to the end of str, not the addresses.
So if str1 points to "123" and str contains "abc", the result will be "abc123".
str does not have sufficient space to hold "abcABC" so the result is undefined

You cannot safely concatenate a new string to a constant string.
Your declarations point to constant strings ("abc" and "ABC").
The correct way is to declare str as a string array, like this:

   char str[100] = "abc";

This makes sure you reserve 100 bytes for the concatenated string, and don't overwrite illegal memory.

-- mnh
Firewall Management 201 with Professor Wool

In this whiteboard video, Professor Wool highlights the challenges, benefits and trade-offs of utilizing zero-touch automation for security policy change management. Watch and Learn!

ganeshkumar_cseAuthor Commented:
guys actually i want to know internal function of the code //str2=strcat(str,str1);

what it is doing?  is it concatinatin two address or strings?

ozoConnect With a Mentor Commented:
the result will be undefined for the two reasons mentioned
if str had been declared as
char str[100] = "abc";
then the result would be "abcABC"
ganeshkumar_cseAuthor Commented:
Hi ozo!!
no i actually compiled that code

it gave me the output as i said earlier!! u guys can check and ping me if  i am wrong!!
You got the result by chance. The program is not correct as you wrote it. Trust us on this.
Your code will crash most of the time, since you are overwriting memory that doesn't belong to your program.
No one said that it would not give that output.
undefined behavior means that the C standard imposes no requirements on the result
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.