A1)
& takes the address of the object to its right, so
&s[0]
takes the address of s[0], which is
identical to the value of
s
A2)
pc[i]
is the value of the ith element of the array pc, not the value of address of ith element. In this case, given that pc is a pointer to a char, then pc[i] is equivalent to
*(pc + i)
, so
*pc[i]
is the equivalent to
*(*(pc+i))
. Since the value of pc[i] can only be in -128...127, the value of
*pc[i]
is likely to cause a program crash, since, except for the case where pc[i] == 0, it is most likely that you do not "own" the address in question.
A3) See A2: in short
pc[i]
is a character, not an address
The code given suggest that you do not understand pointers very well. Most C programmers would have written this something like
char *find_char(char c, const char *s)
{
while(*s) {
if( *s == c )
return s;
s += 1;
}
return NULL;
}
Note that we declare s as
const char *
This does 2 things, 1) the complier will make sure that we don't accidentally assign a value to s, and 2) since the compiler knows that the values that s points to can't be changed, it may do some optimizations that it would not be able to do otherwise. Also,
const char *s
declares a pointer to const char, which means that we can move s, but not assign a value to it. If we wanted to declare a pointer that could not be moved, but we wanted to be able to change the value that it points to, that would be
char * const s
. Logically then,
const char * const s
is a const pointer to const char, i.e. we can't move the pointer, or assign a new value to what it points to.
Since we do have a pointer to a string of characters that ends in'\0', we can simply move the pointer forward until we either find the char we are interested in
*s == c
or we get to the end of the string
*s == '\0'
. I could have written
while(*s != '\0')
in the while loop, but I've taken advantage of the fact that in C/C++ any non-zero value is treated as true. So if the passed in array is "Hello World!", then the value of the s[0] is 'H', decimal 72, which is not zero, and so on until after the '!', when the ending character is '\0' which has the decimal value of zero.
Actually, though an experienced C programmer would probably call
strchr()
, which would might make use of assembler instructions that are optimized for this type of thing.