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.
Related
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
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].
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.
Consider a simple example
Eg: const char* letter = "hi how r u";
letter is a const character pointer, which points to the string "hi how r u". Now when i want to print the data or to access the data I should use *letter correct?
But in this situation, shouldn't I only have to use the address in the call to printf?
printf("%s",letter);
So why is this?
*letter is actually a character; it's the first character that letter points to. If you're operating on a whole string of characters, then by convention, functions will look at that character, and the next one, etc, until they see a zero ('\0') byte.
In general, if you have a pointer to a bunch of elements (i.e., an array), then the pointer points to the first element, and somehow any code operating on that bunch of elements needs to know how many there are. For char*, there's the zero convention; for other kinds of arrays, you often have to pass the length as another parameter.
Simply because printf has a signature like this: int printf(const char* format, ...); which means it is expecting pointer(s) to a char table, which it will internally dereference.
letter does not point to the string as a whole, but to the first character of the string, hence a char pointer.
When you dereference the pointer (with *) then you are referring to the first character of the string.
however a single character is much use to prinf (when print a string) so it instead takes the pointer to the first element and increments it's value printing out the dereference values until the null character is found '\0'.
As this is a C++ question it is also important to note that you should really store strings as the safe encapulated type std::string and you the type safe iostreams where possible:
std::string line="hi how r u";
std::cout << line << std::endl;
%s prints up to the first \0 see: http://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx, %s is a character string format field, there is nothing strange going on here.
printf("%s") expect the address in order to go through the memory searching for NULL (\0) = end of string. In this case you say only letter. To printf("%c") would expect the value not the address: printf("%c", *letter);
printf takes pointers to data arrays as arguments. So, if you're displaying a string (a type of array) with %s or a number with %d, %e, %f, etc, always pass the variable name without the *. The variable name is the pointer to the first element of the array, and printf will print each element of the array by using simple pointer arithmetic according to the type (char is 1 or 2 bytes, ints are 4, etc) until it reaches an EOL or zero value.
Of course, if you make a pointer to the array variable, then you'd want to dereference that pointer with *. But that's more the exception than the rule. :)
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)