user1334858
user1334858

Reputation: 1935

Reseting a char pointer to the top of an array

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?

Upvotes: 0

Views: 72

Answers (4)

Richard
Richard

Reputation: 61409

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;

Upvotes: 1

Ryan Amos
Ryan Amos

Reputation: 5452

At the end of the loop, *substring will be 0. That's the condition for the loop to end:

while(*substring)

So while( (the value pointed to by substring) is not equal to 0), do stuff

But then *substring becomes 0 (i.e. end of string), so *substring will point to NULL.

If you want to bring it back to H, do substring - length

However, the function you are writing already exists. It's in string.h and it's size_t strlen(const char*) size_t is an integer the size of a pointer (i.e. 32 bits on 32 bit OS and 64 bits on 64 bit OS).

Upvotes: 0

Anshul
Anshul

Reputation: 1

Pointer once moved will not automatically move to any another location. So once the while loop gets over the pointer would be pointing to NULL or precisely '\0' which is a termination sequence for the string. In order to move back to the length of string just calculate the string length, which you already are doing by incrementing the length variable. Sample code:

#include<stdio.h>
int main()
{
  char name1[10] = "test program";
  char *name = '\0';
  name = name1;
  int len = strlen(name);
  while(*name)
  {
    name++;
  }
  name=name-len;
  printf("\n%s\n",name);
}

Hope this helps...

Upvotes: 0

Sebastian
Sebastian

Reputation: 7720

It's pointing at the NULL-terminator of the array. Just remember the position in another variable, or subtract length from the pointer.

Upvotes: 0

Related Questions