Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the difference between char *a and char a[20]?
Please show me a simple example for an explanation. Don't make it too complex.

Thanks in advance!
Posted
Updated 29-Mar-11 23:31pm
v2

char* a declares a pointer to a char. You can re-assign a anytime:

char* a = "a string";
a = "another string";


char a[20] declares a fixed size array. You can't change the value of a, but you can chande the content of the array:

char a[20] = "a string";
//this will not compile
a = "another string";
//but this will
strcpy(a, "another string");
//be carefull though not to copy more than 20 characters
//or you will have a buffer overflow
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 30-Mar-11 14:38pm    
Correct, my 5.
--SA
If you're interested, there is a more in-depth discussion here ->
When declare char Str[16] then Str is a pointer?[^]
 
Share this answer
 
Comments
Manfred Rudolf Bihy 30-Mar-11 7:21am    
Good link! 5+
Sergey Alexandrovich Kryukov 30-Mar-11 14:40pm    
I don't know if it helps, but... my 5. I doubt, because that old discussion was almost a flame war :-) however, the final state of it looks like a consensus. On this page, the Answer by Olivier explains it all.
--SA
char *a is only a pointer to a character and besides the space for the reference variable there is no space alotted for storing anything.
char b[20] reserves space for 20 characters that can be readily used.

This page has an good description: http://c-faq.com/aryptr/index.html[^]

Cheers,
 
Share this answer
 
v2
Comments
Аslam Iqbal 30-Mar-11 5:46am    
"char *a is only a pointer to a character" Really? char *a is a pointer and it can be dynamically allocated any length of character. bytheway it was too close. my 4
Niklas L 30-Mar-11 7:00am    
It only points to the first character. It doesn't point to any other characters in the sequence.
Manfred Rudolf Bihy 30-Mar-11 7:13am    
That's what I said. It is just a pointer with no memory allocated for any chars. I'm not sure what you are talking about, but if you want you can try to explain.
(And a 4 is OK by me :) )

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900