am a bit confused about something in string of characters and pointers regarding c++ language ..
well, i came to know that a name of an array of characters is actually the address of it's first element and i also know that The cout object assumes that the address of a char is the address of a string, so it prints the character at that address and then continues printing characters until it runs into the null character (\0).
but here is the interesting part i tried this code in codeblocks
char arr[10]="bear";
cout <<&arr<<endl; // trying to find the address of the whole string
cout<<(int *)arr<<endl; // another way of finding the address of the string
cout<<(int *)arr[0]<<endl; // trying to find the address of the first element
what came on the screen was as follows
0x22fef6,
0x22fef6,
(0x62) <<<< My question is , what the heck is that? .. If the arrayname holds the address of the first element , shouldn't the first element address be " 0x22fef6 " ???????????????????
The [] operator does not return an address but dereferences the pointer at the given offset.
You could write an equivalent to the [] operator as follows:
char arr[10] = "bear";
char c = *(arr+0); // == arr[0] == 'b'
That is, you take the pointer arr, increase it by 0 char and then dereferences it to get it's value.
char arr[10]="bear";
cout <<&arr<<endl;
cout<<(int *)arr<<endl;
cout<<(int *)(arr+0)<<endl; // increases the address by 0
cout<<(int *)(&arr[0])<<endl; // the address of the value at index 0
This would do what you have expected it to do.
arr[0] equals *(arr + 0); you dereference the pointer and obtain the value it holds. To get what you want you need to reference the element, like &arr[0].
Related
Am I able to get the whole number out of char table? For example:
char *table[]={"A","123","2"};
I want to display number 123, but whenever i call
cout<<*table[1];
I get
1
Am I able to fix this ?
When writing char *table[]={"A","123","2"}, your declaring an array of char pointers. In a sense this is a 2 dimensional array and you would print "123" using:
for( unsigned i=0; table[j][i]!='\0'; ++i ) //given j = 1
{
cout << table[j][i];
}
Output:
123
If you look at an operator precedence table for C++, you will find that array subscripting [] is higher precedence than pointer dereferencing *. This, then, is what is happening.
table is an array of pointers. The pointers in the array point to the first character of a string. The next character in the string is simply the next char in memory. The end of the string is the first character whose value is (as an integer) 0, called the null terminator.
When you access table[1], you get the element in the array at index 1, a pointer to a char, which represents a string. When you access *table[1], you get the element in the array at index 1, a pointer to a char, and then dereference that pointer, to get the char it points to.
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
I saw that a potential job interview for a C++ programmer position could ask you this question:
Explain what the following C++ code segment does.
char *aryA = "Data Structures";
char *aryB, *aryC;
aryB = new char[20];
aryC = aryB;
while (*aryB++ = *aryA++);
cout << aryC << endl;
I've been looking at it for a while, but I don't think I am understanding the while loop. So to me it would seem that the while loop is saying to cout aryC so long as the two pointers are equal. But, both pointers are being incremented by one, which I take to mean which char value in the array is being looked at. But if they are the same and both are being increased by one, wouldn't they always be equal? And there's another thing. The values for the array of chars aryB is not defined; we only know there are 20 values in the array. So how can you compare aryA and aryC in the first place?
If anyone can take the time to explain this code segment to me, I would really appreciate it. I am having issues running visual studio, so I can't just run it myself, but even if I could I think I would still benefit from someone teaching me.
It's quite easy, *aryB++ = *aryA++ can be seen as
*aryB = *aryA;
aryB++;
aryA++;
which just assign the character pointed by aryA to aryBand then increment both (to move on next character. The while is executed until the NUL terminating character is found, which is caught by the fact that the = operator (which is not ==) returns the assigned value.
Saving aryB to aryC before the while is just a way to keep the pointer to the beginning of the copied string, since you lose it by then incrementing aryB.
aryB = new char[20]; sets aryB to a new character array.
aryC = arB; sets aryC as a reference to aryB.
while (*aryB++ = *aryA++); This one is more complicated. It will set the current value at aryB to the current value at aryA while the current value at aryA is not false (0), then move where both pointers forward one (remember that all c strings end with \0, which evaluates to 0). This also changes the value of aryC, but not what it points to. In the end, aryA is copied into aryC.
aryB is a pointer that points to an address in memory. By placing * in front of pointer (*aryB), you access the actual data at that memory address. ++ increments the pointer by 1, which makes it to point to the next memory address. Inside while() you do not compare (the operator is not ==), the assignment operator is used (=). This means that you will be copying data from memory aryA to aryB. Also aryC = aryB means that aryC points to the same memory address as aryB (points to the first element of the array). In other words by modifying data at aryB, you also modify it for aryC.
char *aryA = "Data Structures";
char *aryB, *aryC;
aryB = new char[20];
aryC = aryB;
We can visualise the memory use and pointer contents like this:
[(char*)aryA]--------------------------v
["Data Structures\0"]
[(char*)aryB]-------------v
[ 20 uninitialised chars ]
^
|
[(char*)argC]-------------/
Then:
while (*aryB++ = *aryA++);
Is processed like this:
*aryB = *aryA - assigns *aryB (the first uninitialised char),
with *aryA (the 'D' in Data)
aryB++, aryA++ - post-increments add one to each pointer
(i.e. move to the 'a' in Data, the 2nd uninitialised value
while (...) - evaluates the assignment, exiting if false
the assignment evaluates to the copied character
only character code 0 / '\0' / NUL converts to false; others to true
We now have:
[(char*)aryA]---------------------------v
["Data Structures\0"]
[(char*)aryB]--------------v
[D ]
^
|
[(char*)argC]-------------/
Repeat. This keeps copying character by character until the data from *aryA is the NUL character, which gets copied but then the assignment evaluates to false and the loop terminates.
While that was all happening, aryC stayed pointing at the start of the new-ed buffer, so it can now be used to stream out the content:
cout << aryC << endl;
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 argument as a pointer to the first element of an array and prints every element until it encounters a zero. ("Null-terminated 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.
char a[]="helloworld";
I want to get address of 'l'?
(a+2) or &a[2] gives lloworld. And adding other ampersand shows error.
Then how to get address of 'l'?
If not possible, please explain?
a + 2 is the address of the third element in the array, which is the address of the first l.
In this expression, a, which is of type char[11], is implicitly converted to a pointer to its initial element, yielding a pointer of type char*, to which 2 is added, giving the address of the third element of the array.
&a[2] gives the same result. a[2] is equivalent to *(a + 2), so the full expression is equivalent to &*(a + 2). The & and * cancel each other out, leaving a + 2, which is the same as above.
How this address is interpreted in your program is another matter. You can use it as "a pointer to a single char object," in which case it's just a pointer to the first l. However, you can also interpret it as "a pointer to the C string contained in the array starting at the pointed-to char, in which case you get "lloworld". It depends on how you use the pointer once you get it.
Both are correct, but if you want to output it you'll have to either:
for C: use an appropriate format string (for C):
printf("address: %p\n", &a[2]);
for C++: avoid string interpretion by cout by casting to a void*:
cout << "address: " << static_cast<void*>(&a[2]) << endl;
I think you want strchr:
char *lAddress = strchr(a, 'l');
This will point to the start of l.
You can print this using printf using the %p descriptor.
strchr will return a pointer to (address of) the first occurrence of a given character in a string.
What do you mean it gives up 'lloworld'. If you use it as a C-string it will still be null terminated. Just start a bit further on in the sentence.