You are here:

C/pointer in ANSI C

Advertisement


Question
Hi, I am quite weak in pointer for C language. Could you please explain to me this coding?


#include <stdio.h>
#include <stdlib.h>

int f(char* str);

int main(void)
{
   char s[] = "Hi";
   printf("%d\n", f(s));
   return EXIT_SUCCESS;
}

int f(char* str)
{
   char* ptr = str;
   while (*str++);
   return str - ptr;
}

My question are:
1. Why the answer is 3
2. What does it mean by return str - ptr?

Thanks for your help

Answer
Hello Zakiah
Before I get to your question, I want to make sure you understand how the string "Hi" is being stored. It is stored as three bytes which are the characters 'H', 'i', and a zero byte to encode the end of the string. Those three bytes are in memory and the first byte of that memory is pointed to by s. Although s is an array, it also acts as a pointer. That pointer is passed to the function f and is assigned to str. The while loop in f uses str to examine each character in the memory until the zero byte is found. The post-increment operator increments str every time a character is examined, and this happens even when the zero byte is found.

Actually, The post increment operator increments str and then returns the old value of str so here are the detailed steps of what is happening.

The str is incremented, but the while loop gets the old value of str and examines what the old value is pointing at. The old value is pointing at 'H', which is not 0, so the loop does not exit. Now, str is pointing to 'i'. Again str is incremented, but the while loop gets the old value of the pointer so it sees the 'i'. Again the loop does not exit because the 'i' is not 0. Now str is pointing to the zero byte. It is incremented again, but the while loop uses the old value of str which is pointing at the zero byte, so the while loop exits.

Notice that str is incremeted three times. It is now pointing to just past the zero byte and is not really pointing to valid memory.  

Next, you should know that pointers are just numbers. They happen to be memory addresses, but still (like room numbers on doors in a hallway), they are just numbers and can be subtracted or added. Subtracting str-ptr shows how far str has gone past ptr. Remember that ptr was assigned the original value of str. The str was incremented 3 times so str-ptr will be 3. That's why the program prints 3.

I hope that helps you understand a little about pointer arithmetic.

Best regards
Zlatlo

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.