array of pointers to characters

Hey,

I've found something strange about of arrays of pointers to characters.
 
const char* a[]={"test1","test2"}

a[0] prints out "test1", and a[1] "test2".

What I don't understand: the array is supposed to contain addresses to places in the free store where actual characters are stored, not whole sequences of characters!
Can any one explain?
"test1" returns a pointer to a memory location with "test1" written in it.
When displaying a pointer to character, the contents of the memory location is displayed

1
2
char* a = "Test1";
cout << a;
Will show Test1 for the same reason
Last edited on
If I understand correctly:

a[0] is a pointer to a memory location where "test1" is stored. But the var on this location isn't really an ordinary character, but an array of characters:

so const char* a[]={"test1","test2"} is not just an array of pointers, but each element points to an array of characters?
Last edited on
closed account (z05DSL3A)
const char* a[]={"test1","test2"} will give you a memory layout somthing like:


─┬─┬─┬─┬─┬─┬──┬─┬─┬─┬─┬─┬──┬─
...│t│e│s│t│1│\0│t│e│s│t│2│\0│...
─┴─┴─┴─┴─┴─┴──┴─┴─┴─┴─┴─┴──┴─
↑ ↑
a[0] a[1]



If you use a print string function and pass it a pointer (a[0]) it will output all the characters in sequence until it reaches the null (\0) character.
Last edited on
Is it because of this?
 
char a="test1";

is not a ordinary character, but an array of characters. That syntax is just so confusing! One should expect that the var a only stores "t" and then ignores everything else (as an int var would ignore all decimals as in "int i=2.9").

Thanks anyway for your help!
char a = 't'; will assign 't' to a as 't' is a character, "test1" is a position in memory so char a = "test1"; is wrong
closed account (z05DSL3A)
Lets try to break this down a bit; char* is a pointer to a char there is nothing special about it.

when you have some code such as: char* a = "test"; the characters test\0 are put into memory and the address of the first character is assigned to the pointer a. So now a points to the letter t.

Functions designed to iterate over the memory that will use the pointer as a starting place and then increment the memory address until they reach \0.
Thanks for all your help, really!
Last edited on
Topic archived. No new replies allowed.