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?

1

5 Answers

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.

3

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;

3

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.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy