tags:

views:

140

answers:

4

If I have a pointer that is pointing somewhere in a string, let's say it is pointing at the third letter (we do not know the letter position, basically we don't know it is the third letter), and we want it to point back to the first letter so we can make the string to be NULL how do we do that?

For example:

if we have ascii as a pointer ascii is pointing now somewhere in the string, and i want it to point at the first char of the string how do i do that?

(Note: I tried saying

int len = strlen(ascii);
ascii -= len;
ascii = '0';

but it is not working, it changes wherever the pointer is to 0 but not the first char to 0)

+12  A: 

You cannot. C and C++ go by the "no hidden costs" rule, which means, among other things, noone else is going to secretly store pointers to beginnings of your strings for you. Another common thing is array sizes; you have to store them yourself as well.

aib
so if u have a pointer pointing somewhere in a string, you can make it point at the first char of that string?
Assuming you know what index you're at. If you have no idea how long the string is, no, as there is no marker indicating the start of a string.
Donnie
But you can assign to pointers. If you have another pointer already pointing to the beginning of your string, you can do `ascii = beginning_of_string`. I'm saying this because you seem to be missing a dereference on your third line: `*ascii` would access the thing pointed at; `ascii` would access the pointer itself.
aib
+1  A: 

First of all, in your code, if ascii is a pointer to char, that should be

*ascii = '\0';

not what you wrote. Your code sets the pointer itself to the character '0'. Which means it's pointing to a bad place!

Second of all, strlen returns the length of the string you are pointing to. Imagine the string is 10 characters long, and you are pointing at the third character. strlen will return 8 (since the first two characters have been removed from the calculation). Subtracting this from where you are pointing will point you to 6 characters before the start of the string. Draw a picture to help see this.

IMHO, without having some other information, it is not possible to achieve what you are wanting to do.

From what I said above, you should be able to work out what you need to do as long as you keep the original length of the string for example.

Tony van der Peet
A: 

No. You, however, can make it point at the last character of the string, which is right before '\0' in every string (it's called zero-terminated string).

What you could do is instead of a char* you could use a pointer to a struct which contains the information you need and the string.

glebm
A: 

It's not guaranteed to work, but you might get away with backing up until you find a null character, and then moving forward one.

while(*ascii) ascii--;
ascii++;
Ken Rose