user3416701
user3416701

Reputation: 39

C++ String to String Conversion

char ch[3];
strcpy(ch,"Hello");
cout<<ch<<" "<<sizeof(ch);

Q1. Why is it printing "Hello" when the size of ch is 3 ?

Q2. If ch is converted from ch[2] to ch[6] (by Implicit Type Conversion) then why is sizeof(ch) still 3 ?

Upvotes: 1

Views: 72

Answers (3)

AliciaBytes
AliciaBytes

Reputation: 7449

You are doing something really dangerous there. This is one of the reasons to use std::string you don't have to check if you go out of bounds for simple copying.

Question 1:
Like others said already, it printing out "Hello" is undefined behavior and anything can happen. But that's not all. Writing out of bounds like you do in your code is dangerous. You basically got a Buffer Overflow, if you look at the example on Wikipedia you'll see that it's nearly the same code you got.

Question 2:
There is no conversion. When you call strcpy(ch, "Hello"); your array ch decays into a pointer. There is no way for strcpy to know how many chars it can safely copy there, since a pointer is nothing more than a memory address. It doesn't know how much memory is available at the location so simply writes everything even if (like in your case) you go out of bounds.

Things like you got in your code is one of the reasons why pointers are being called unsafe.

Upvotes: 3

mah
mah

Reputation: 39847

I am assuming when you typed char a[3]; you meant char ch[3];.

A1: When you declare an array of some size, it's up to you to not exceed it. If you do exceed it as in this case, you get undefined results.

A2: You cannot convert it like this so it's a non-issue.

Upvotes: 3

Ilya Kobelevskiy
Ilya Kobelevskiy

Reputation: 5355

strcpy does not do a size check, so it simply writes "Hello\0" at memory address of a, overwriting whatever is located after a in memory.

There are no conversions performed, ch is char[3] as it was before strcpy.

Upvotes: 3

Related Questions