Skip to content

Reseting a char pointer to the top of an array

An answer to this question on Stack Overflow.

Question

I am writing a function and I need to count the length of an array:

while(*substring){
    substring++;
    length++;
}

Now when I exit the loop. Will that pointer still point to the start of the array? For example:

If the array is "Hello"

when I exit the loop with the pointer be pointed at:

H or the NULL?

If it is pointing at NULL how do I make it point at H?

Answer

Strings in C are stored with a null character (denoted \0) at the end.

Thus, one might declare a string as follows.

char *str="Hello!";

In memory, this will look like Hello!0 (or rather, a string of numbers corresponding to each letter followed by a zero).

Your code looks like this:

substring=str;
length=0;
while(*substring){
    substring++;
    length++;
}

When you reach the end of this loop, *substring will be equal to 0 and substring will contain the address of the 0 character mentioned above. The value of substring will not change unless you explicitly do so.

To make it point at the beginning of the string you could use substring-length, since pointers are integers and may be manipulated as such. Alternatively, you could memorize the location before you begin:

beginning=str;
substring=str;
length=0;
while(*substring){
    substring++;
    length++;
}
substring=beginning;