user220755
user220755

Reputation: 4446

Pointers in c (how to point to the first char in a string with a pointer pointing somewhere else in the same string)

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)

Upvotes: 1

Views: 1630

Answers (4)

Ken Rose
Ken Rose

Reputation: 11

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++;

Upvotes: -1

glebm
glebm

Reputation: 21090

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.

Upvotes: 0

Tony van der Peet
Tony van der Peet

Reputation: 824

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.

Upvotes: 1

aib
aib

Reputation: 46941

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.

Upvotes: 12

Related Questions