G
G
German2019-01-13 02:24:55
C++ / C#
German, 2019-01-13 02:24:55

String or char*?

Now I tend to use char arrays, but what is better to use?
And what's the difference between char* and char[]?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zuko3d, 2019-01-13
@zuko3d

Use std::string to store text. You don't have to keep track of memory and it's easier to access specific elements, such as the last character.
Iterating over all characters is also more convenient:

string str = "hello!";
for(auto& c: str) {
    c += 1;
}
cout << str << endl;

R
res2001, 2019-01-13
@res2001

And what's the difference between char* and char[]?

char* str1 = "Hello world!";
char str2[] ​​= "Hello world!";
The difference between str1 and str2 is that str1 is an lvalue while str2 is not.
Those. with str1 you can for example do str1 = str1 + 1; but not with str2.
In terms of memory:
In the case of str1, 2 entities are stored in memory: 1) the string itself "Hello world!" 2) a pointer to which the address of the string is assigned. So you can assign a different value to a pointer.
In the case of str2, there is no pointer in memory, there is only a string. The compiler knows the string address and uses it when needed. But it is no longer possible to assign a new value to this address.
We can assume that char str[]; it's the same as char * const str;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question