How do I get the address of elements in a char array? - c++

I have a char array and I need to get the address of each element.
cout << &charArray
gives me a valid address, However if I try to get the address of a specific element, it spits out garbage:
cout << &charArray[0]

std::cout << (void*) &charArray[0];
There's an overload of operator<< for char*, that tries to print the nul-terminated string that it thinks your pointer points to the first character of. But not all char arrays are nul-terminated strings, hence the garbage.

You can do something like
&charArray + index * sizeof(char)

Related

Weird output when using char double pointer

I get really weird output from the last cout statement, no idea what would be causing this:
char ex1_val = 'A';
char* ex1;
ex1 = &ex1_val;
cout << *ex1 << endl;
char** ex2;
ex2 = &ex1;
cout << *ex2 << endl;
Here's my output:
A
A����
ex2 is declared as char**, which means it's a pointer to a pointer to char.
When you print the contents of *ex2, you're dereferencing it once, so type of *ex2 is a pointer to char.
Effectively, the compiler assumes, that you want to print a C-style string, which is a NULL-terminated string. So it prints all bytes stored in memory, starting from A stored in ex1_val, followed by random values stored directly after that, until a NULL character is encoutered.
This is actually a very bad situation, as you never know when or if there's a NULL in memory. You might end up trying to access a memory area you're not allowed to use, which may result in crashing the application. This is an example of an undefined behaviour (UB).
To print out the actual contents of ex1_val via the ex2 pointer, you'd need to make it like this:
cout << **ex2 << endl;
where typeof(**ex2) is an actual char.
When you dereference ex2 (in *ex2) you get a pointer to a char (i.e. char*), and the operator<< overload to handle char* outputs it as a C-style zero-terminated string.
Since *ex2 doesn't point to a zero-terminated string, only a single character, you get undefined behavior.
You want to do cout << **ex2 << endl;
ex2, as you have declared it, as a pointer to a pointer to a character. Doing *ex2 only gets you the address of the pointer it is pointing to.

c++ pointer to specific element in char array returns all elements after the specified one

To recreate this little problem of mine use this code (Yes it's bruteforced and could be slimmed down):
char hello[] = "John";
char *ptr1 = &hello[0];
char *ptr2 = &hello[1];
char *ptr3 = &hello[2];
char *ptr4 = &hello[3];
std::cout << ptr1 << "$";
std::cout << ptr2 << "$";
std::cout << ptr3 << "$";
std::cout << ptr4 << "$";
as you may see after trying this code, it returns the following:
John$ohn$hn$n$
I have no idea why it takes all elements after the specified one.
Any help?
It's because you're printing the pointer, not the thing it points to. And char pointers in C programs often point to the start of a char[] which represents a '\0'-terminated string. That is why std::ostream (of which cout is an instance) has an overloaded << operator that outputs the entire string, up to the terminator.
To print just the character, dereference the pointers first:
std::cout << *ptr1 << "$";
You could also use references instead, which are treated largely as a substitute for the value itself:
char &ptr1 = hello[0];
ptr1 through ptr4 are also pointers to characters, therefore << will treat them as strings, and print them as such, giving you what you saw.
If you just want the characters at each location, lines of the form:
char ch1 = hello[0];
will work, as will changing the output to:
std::cout << *ptr1 << "$";
Your question seems to be based on some completely unfounded expectations. It looks like you expected your code to print a single character for each cout << ... line. But why did you expect it to do that? What you send to cout in your code is actually a char * pointer. Why did you expect cout to dereference that pointer for you and print the character? A normal thing to expect would be to see the pointer value in the output (the address), not the character value.
So, the question you should really be asking is not "why it prints several characters from my array?". The question you should really be asking is "why it prints any of my characters at all?". You never dereferenced your pointer. Yet, instead of pointer value the output contains a sequence of char objects that pointer was pointing to. I.e. apparently cout decided to dereference your pointer for you, even though you never explicitly asked it to. That is the question you should be asking: why did my pointer get dereferenced at all?
And the answer is that [const] char * pointers receive special treatment when sent to cout using << operator. There's a dedicated overloaded version of << operator introduced specifically for that purpose. That version of << operator will treat char * pointers as pointing to the beginning of a C-string. And that operator will output the entire C-string all the way to the zero terminator character. That is exactly what is happening in your experiment.
Note that if you use any other pointer type (like int *) for example, you will not see the pointed value (or values) in the output. You will see the implementation-dependent representation of the pointer itself.
if you want to print value at particular address then :
std::cout << *ptr1 << "$";
std::cout << *ptr2 << "$";
std::cout << *ptr3 << "$";
std::cout << *ptr4 << "$";
I am not entirely sure but if it cout receives a char pointer, it will print, everything until it reaches a blank in memory, (C style character string), and if you just want to print a character, you should print only the content of the variable, that means just pass the content not the memory location...

C++ char pointer

Why does the following happen?
char str[10]="Pointers";
char *ptr=str;
cout << str << "\n"; // Output : Pointers
int abc[2] = {0,1 };
int *ptr1 = abc;
cout <<ptr1 << "\n"; // But here the output is an address.
// Why are the two outputs different?
As others have said, the reason for the empty space is because you asked it to print out str[3], which contains a space character.
Your second question seems to be asking why there's a difference between printing a char* (it prints the string) and int* (it just prints the address). char* is treated as a special case, it's assumed to represent a C-style string; it prints all the characters starting at that address until a trailing null byte.
Other types of pointers might not be part of an array, and even if they were there's no way to know how long the array is, because there's no standard terminator. Since there's nothing better to do for them, printing them just prints the address value.
1) because str[3] is a space so char * ptr = str+3 points to a space character
2) The << operator is overloaded, the implementation is called depending on argument type:
a pointer to an int (int*) uses the default pointer implementation and outputs the formatted address
a pointer to a char (char*) is specialized, output is formated as a null terminated string from the value it points to. If you want to output the adress, you must cast it to void*
The empty space is actually Space character after "LAB". You print the space character between "LAB" and "No 5".
Your second question: You see address, because ptr1 is actually address (pointer):
int *ptr1;
If you want to see it's first member (0), you should print *ptr1

Making strings by pointers

I have learned that a pointer points to a memory address so i can use it to alter the value set at that address. So like this:
int *pPointer = &iTuna;
pPointer here has the memory address of iTuna. So we can use pPointer to alter the value at iTuna. If I print pPointer the memory address gets printed and if I print *pPointer then the value at iTuna gets printed
Now see this program
char* pStr= "Hello !";
cout<< pStr << endl;
cout<< *pStr << endl;
system("PAUSE");
return 0;
There are a lot of stuff I don't understand here:
In "Hello !" Each letter is stored separately, and a pointer holds one memory address. So how does pStr point to all the letters.
Also When I print out pStr it prints Hello !, not a memory address.
And when I print out *pStr it prints out H only not all what pStr is pointing too.
I really can't understand and these are my concerns. I hope someone can explain to me how this works ad help me understand
"Hello !" is an array of type char const[8] and value { 'H', 'e', 'l', 'l', 'o', ' ', '!', 0 }. pStr is a pointer to its first element; its last element has the value 0.
There is an overload in the iostreams library for a char const * argument, which treats the ar­gu­ment as a pointer to the first element of an array and prints every element until it encounters a zero. ("Null-ter­mi­nat­ed string" in colloquial parlance.)
Dereferencing the pointer to the first element of an array gives you the first element of the array, i.e. 'H'. This identical to pStr[0].
1-) Since pStr points to a char, it actually points to the beginning of an array of a null terminated string
2-) cout is overloaded with a char * argument. It will print out ever character in the string until it reaches the null character
3-) You are dereferencing the pointer to the first element of the character array.
1-) In "Hello !" Each letter is stored seperatly, and a pointer holds
one memory adress. So how does pStr point to all the letters.
The letters are stored in that order in each memory cell with an extra final cell
holding 0 to mark the end.
2-)Also When i print out pStr it prints Hello ! not a memory adress.
The cout << understands that you are pointing at a string and so prints the string.
3-)And when i print out *pStr it prints out H only not all what pStr
is pointng too.
The * means you are askign for the value at that address. cout << knows that the address holds a char and so prints the char.
Your understanding of pointers is correct in all respects.
Your problem is that the << operator has been overridden for various datatypes on a stream. So the standard library writers have MADE the operator << do something specific on any variable of the type char * (in this case the something specific means output the characters at that address until you get to the end of string marker) as opposed to what you expect it to do (print an address in decimal or hex)
Similarly the << operator has been overridden for char to just output a single character, if you think about it for a bit you will realise that *pStr is a dereferenced pointer to a character - that is it is a char - thus it just prints a single char.
You need to understand concept of strings as well. In C and C++, string is a few characters (char's) located one after another in a memory, basically, 'H','e','l','l','o','\0'. Your pointer holds memory address of the first symbol, and your C++ library knows that a string is everything starting this address and ending with '\0'.
When you pass char* to cout, it knows you output a string, and prints it as a string.
Construction *pStr means "give me whatever is located at address stored in pStr". That would be char - a single character - 'H', which is then passed to cout, and you get only one character printed.
A pointer, *pStr points to a specific memory address, but that memory address can be used not only as a single element, i.e. a char, but also as the beginning of an array of such elements, or a block of memory.
char arrays are a special type of array in C in that some operations handle them in a specific way: as a string. Hence, printf("%s", ... and cout know that when given a char * they should look for a string, and print all the characters until the terminating null character. Furthermore, C provides a string library with functions designed to manipulate such char * as strings.
This behavior is just as you'd expect from your own analysis: de-referencing pStr simply gives you the value at the memory address, in this case the first element of an array of chars in memory.
A pointer to an array (a C style string is an array of char) is just a pointer to the first element of the array.
The << operator is overloaded for the type char* to treat it as a C-style string, so when you pass it a char* it starts at the pointer you give it and keeps adding 1 to it to find the next character until it finds the null character which signals the end of the string.
When you dereference the pointer you the type you get is char because the pointer only actually points to the first item in the array. The overload of << for char doesn't treat it as a string, just as a single character.
Using strings like this is C-style code. When using C++ you should instead use std::string. It is much easier to use.

Why doesn't a character array return a memory address when called directly?

I understand from here that the name of an array is the address of the first element in the array, so this makes sense to me:
int nbrs[] = {1,2};
cout << nbrs << endl; // Outputs: 0x28ac60
However, why is the entire C-string returned here and not the address of ltrs?
char ltrs[] = "foo";
cout << ltrs << endl; // Outputs: foo
Because iostreams have an overload for char * that prints out what the pointer refers to, up to the first byte that contains a \0.
If you want to print out the address, cast to void * first.
cout has operator<<() overloaded for char* arrays so that it outputs every element of the array until it reaches a null character rather than outputting the address of the pointer
cout, and generally, C++ streams, can handle C strings in a special way. cout operators <<, >> are overloaded to handle a number of different things, and this is one of them.