Without using the ampersand it assigns the pointer a reference but when you try and get the value from the reference using the cout function, it gives me what looks this: Uï∞âSVWUⁿï]♀ï≈@♦♠
I was wondering what I'm doing wrong, and how to fix it if possible. I've tried tons of combinations for experimenting but I've gotten to a point to where I just want to know what the right thing to do is. This would add to my experience and hopefully help me with the concept. Also, I'm a little sketchy with terms and I don't mind to be corrected in a nice way. :) Thank you much in advance.
I'm not sure what you are trying to do, but you are definitely confusing pointers with arrays with pointers to arrays.
Let's look at what your code does.
char aPointer[] = "add";
Declares an array of 4 characters: 'a', 'd', 'd', '\0' (NULL)
char* pCarrier[sizeof(aPointer)];
Declares an array of sizeof(aPointer) pointers to characters.
sizeof(aPointer) is 4, so you create an array of 4 pointers.
This array occupies 16 bytes of memory on a 32-bit machine.
pCarrier[sizeof(aPointer)] = aPointer;
aPointer referenced by itself is the address of the first array
in memory. sizeof(aPointer) is 4. Arrays in C are indexed zero-based,
so the valid indices in an array of 4 elements are 0, 1, 2, and 3.
You assign index 4 the address of the aPointer array. This is a
memory stomp. Since you don't explicitly assign any of the other
elements of pCarrier, they are all uninitialized (random garbage).
cout << *pCarrier;
*pCarrier is the same as pCarrier[0]. Each element of pCarrier is
a char*, so this prints out the string pointed to by pCarrier[0]
which we established is random garbage.
Well figured it out. I am noob it seems. The point of this is to make a pointer that pointed to an array of char and have the ability to return the array of char. If you do:
It only gives you the first letter or 'a' or the reference of aPointer[0]. So you would have to make the array of pointers and assign each element the reference to that specific char since each one has its own address in memory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int i;
char aPointer[] = "I love earth and all its creatures.";
char *pCarrier[sizeof(aPointer)];
for (i = 0; i < sizeof(aPointer); i++)
pCarrier[i] = &aPointer[i];
cout << *pCarrier;
return 0;
}
//returns the array of char in aPointer.
Thank you guys for helping me. This really did help. :).
If any of you see a better way to do this, I wouldn't mind the advice. I'm new and I still don't have the gist of things around C++.
pCarrier is a pointer to a character. It can also be interpreted as a pointer to an array of characters, or a C-style string.
The expression *pCarrier has type char -- that is, a single character -- and hence you only see one character printed. If you wanted to see the whole string printed, all you need to do is