I don't understand what a pointer does in the for
loop. What does the *p
do in the following loop?
char str[128] = "Some Text"; char *p; for (p = str; *p /*what does this mean?*/; p++) { // Code }
I do understand the rest, but why isn't *p
like p > 3
or something like that?
Why is it alone?
Why is it written that way?
we assign the pointer to the array str to p. In C the following assignments have the same effect: p = &str[0]; p = str; “By definition, the value of a variable or expression of type array is the address of element zero of the array” (K & R (2)).
C. In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.
In a Boolean context such as the condition of a for
loop, each expression in C evaluates to true (non-zero) or false (zero).
You want the for
loop to terminate, when it reaches the end of the string.
In C, each string is terminated with the character '\0'
, which is practically 0
. So, when the for
loop reaches the end of string, *p
evaluates to '\0'
, which is 0
, which evaluates to false, which terminates the for
loop.
The for loop will terminate if whatever lies between the two ;
in the statement is zero (false). *p
dereferences p and returns the char
, p
points to. According to Dennis Ritchie "C treats strings as arrays of characters conventionally terminated by a marker". That marker is the null character with (ASCII) value of zero. So, this for loop :
for (p = str; *p; p++)
is equivalent to these
for (p = str; *p != '\0'; p++) for (p = str; *p != 0; p++) for (p = str; p[0] != '\0'; p++)
Another name for the null terminating character is sentinel or according to Donald Knuth "dummy value" (Art of Computer Programming, Volume 1). Here is a diagram of the str
string, the indexes (offsets from the start) of each character and the values at each index :
For completeness and after a request at the comments here is what the debugger sees in the memory block that str
occupies :
0x00007fffffffe6a0: 0x53 0x6f 0x6d 0x65 0x20 0x54 0x65 0x78 0x74 0x00 0x00 0x00 0x00 0x00 0x00 0x00 S o m e T e x t
p
points to at the start of the for loop.t
with hex value of 0x74
. After that you have the string's null character 0x00
. Then you see a few more null characters because I built in debug mode and the compiler zero-initialized. Normally you would see garbage (seemingly random values)I understand you are on precipitous learning curve at the moment with pointers in C, but eventually you'll be able to say "I C the point"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With