0

What is char * ?

i am not able to understand the difference between char array and char * can you have any idea about that please tell me..

13th Feb 2018, 8:23 AM
Parth Yadav
Parth Yadav - avatar
3 Answers
+ 5
I suppose these links can explain better than I could apparently ; ) https://www.quora.com/What-is-the-difference-between-char*-and-char https://www.geeksforgeeks.org/whats-difference-between-char-s-and-char-s-in-c/ Hth, cmiiw
13th Feb 2018, 9:20 AM
Ipang
+ 4
@Freddy thanks for corrections! (I have edited my post)
13th Feb 2018, 11:22 AM
Ipang
+ 1
Here is a copy from Ipang's answer with my comments in between (the lines with /// in front): int main() { // a char array requires null terminator, /// No it doesn't. A char array is just an array of chars. /// A char is an 8 bit signed datatype that can hold values /// from -128 to 127. If you want to use a char array as a /// C type string you indeed need a '\0' terminator. // that's why we allocated 6 elements here // but we only initialize 5 of them, // the 6th one is null terminator ('\0'). /// You only initialise 5 of them, and you let it to chance /// that the 6th field is initialised to '\0'. /// To do it properly, declare it as: char arr[6] = {'h','e','l','l','o','\0'}; /// Or even better: char arr[] = "hello"; /// Why that is better: because it shows your intention. /// The first version declares an array, the second a C type /// string. Do show how you are using your variables! The /// "hello" literal already contains the '\0' terminator /// try: cout << sizeof("hello") << endl; /// it will give 6 (5 characters + '\0' terminator) // a char pointer looks like a string, // uses double quotes, and it doesn't // require us to add null terminator. char *ptr = " world"; /// though it isn't the same, try the following: arr[2] = 'u'; ptr[2] = 'u'; /// the first one works, as arr is actually your memory /// the second doesn't, as you are now trying to modify /// memory that isn't yours. /// Apart from that: char* p = "yourText"; is depricated /// in C++. Do not use it. // outputs "hello world" cout << arr << ptr << endl; /// this only workes by chance, as a modern C++ compiler /// seems to initialise the 6th field to 0, do not count /// on all compilers (especially in older standards) to do so. Have a look at this youtube film about C strings, I hope that makes it somewhat clearer: https://www.youtube.com/watch?v=VCIMLkej128&index=5&list=PLULj7scb8cHgDLDHcRcJ1osiOORic86wR
13th Feb 2018, 10:34 AM
Freddy