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.
cout in C++? You have printf right there in the cstdio header. And that code isn't getting the address. That code is printing the address. You already get the address with the code you and everyone has shown: a + 2 or &a[2]. Your problem is in printing that value so it looks like an address.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.
char *. cout uses this as a string. Do you want the raw address - then cast it to void *.
static_cast<void *>(&a[2])for an address output. If so, its a possible duplicate of this: stackoverflow.com/questions/10817278/…