- char *a
2.char a[]
3.char *a = new char[size]
Difference between the Char declarations
- char *a;
a is a pointer to a character. - char a[100] ;
a is the name of a character array. Here the size of that array is 100. That is , a points to the starting location of the 100 blocks of char which have been allocated continuously. The memory is allocated at compile time. - char *a = new char[100] ;
a is a pointer that has been allocated memory of 100 char blocks. The memory is allocated at runtime.
The essential difference between 2 and 3 is that in case 2, you cannot shift the a pointer to any other location later in the code.
char a[100];
a = new char[20] ; // Invalid … will give an error.
This is because a is the name of an array. You can also consider it to be a constant pointer.
In case 3 , you can shift the a pointer later in your code as well if you wish.
char *a = new char[100];
a = new char[20];
This code will work perfectly fine and won’t give any error.
Note - Do not use this in practice as there is a memory leak in this code snippet.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.