strlen
vs sizeof
strlen
method is used to find the length of an array whereassizeof
method is used to find the actual size of data, eg:1
2
3
4
5
6
7
8
9
10
11strcpy(str,"this is a test");
lengthStr = strlen(str);
// lengthStr is 14 dont include \0
sizeStr = sizeof(str);
// sizeStr is 15 iclude \0
char myStr[20] = "this is a test";
lengthMyStr = strlen(myStr);
// lengthMyStr is 14
sizeMyStr = sizeof(myStr);
// sizeMyStr is 20strlen
count the numbers of character in a string whilesizeof
return the size of an operand.strlen
looks for the null value of variable butsizeof
doesn't care about the variable value.
char []
vs char*
- char is a primitive data type in
c++
, can hold a single character whilechar[]
is an array of characters, whereaschar*
is a pointer to one or morechar
objects and can be used as a string. - eg, the output is:
1
2
3
4
5
6
7
8
9
10
11
12
using namespace std;
int main()
{
char charArray[] = "Hello";
char *charPointor = charArray;
cout << charArray << " " << charPointor << endl;
cout << *charArray << " " << *charPointor << endl;
return 0;
}Hello Hello
andH H
. Thechar*
** in C++ is a pointer used to point to the first character of the character array.** ## constructor and shadow copying An questionable program with an error in copying constructor.
1 |
|
using the object sayHello
of class MyString
which delegated to function UssMyString()
, invoked in UseMyString(sayHello);
. Delegating work to this function result in object sayHello
in main()
to be copied into parameter str
. This operation take str
as a parameter by value and not by reference(&
). Hence the pointer value in sayHello.buffer
has simply been copied to str
, that is, sayHello.buffer
points the same memory location as str.buffer
. Now the two objects of class MySyring
both point the same memory location. When main()
ends, sayHello
goes out of scope and is destroyed. This time, however, delete[] buffer;
repeats a call to delete on a memory address that is no longer valid.
note that: in
void UseMyString(MyString str)
,str
is similar toMyString
inMyString(const char *initString)