vijay
vijay

Reputation: 2034

how to get address of particular element in a string

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?

Upvotes: 0

Views: 1201

Answers (5)

smocking
smocking

Reputation: 3709

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;

Upvotes: 3

James McNellis
James McNellis

Reputation: 355039

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.

Upvotes: 7

Ed Heal
Ed Heal

Reputation: 59997

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.

Upvotes: 0

pb2q
pb2q

Reputation: 59607

strchr will return a pointer to (address of) the first occurrence of a given character in a string.

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

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.

Upvotes: 0

Related Questions