strlen vs
sizeof
strlenmethod is used to find the length of an array whereassizeofmethod 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 20strlencount the numbers of character in a string whilesizeofreturn the size of an operand.strlenlooks for the null value of variable butsizeofdoesn'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 morecharobjects 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 HelloandH 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),stris similar toMyStringinMyString(const char *initString)