-3

I was learning about recursion using c and there was a question with an array say for example:

void main(){
     char str[100];
     --snip--
     if(*str == 'c')
        count++;
     --snip--
}

here *str is the value retrieved from the pointer that points to first character of the string str.

My question is what is pointer derefrencing and can i do as follows:

--snip--
str+=1;
--snip--

to get new pointer pointing to the next location of another character in that string?

1 Answers1

5

You cannot increment an array, but you can increment a pointer to an element of the array:

char str[100];
char *pointer = str; //points to the begin
pointer++; //points to the second element
*pointer = 'a'; //sets the second element

str has the type char [100], in some expressions it decays to (e.g. behaves like) a pointer, but it is not a pointer, you cannot assign to str. str = ... or str+=1; is invalid, you can only assign something to an element of an array, not the array itself.

Therefore you have to create a pointer to an element of the array and then you can increment the pointer.

mch
  • 9,424
  • 2
  • 28
  • 42