-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?

2
  • This may help too: stackoverflow.com/questions/1704407/… Commented Mar 2, 2021 at 9:23
  • "can i do as follows" - If you tried it, you would instantly notice that you cannot. Commented Mar 2, 2021 at 9:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

is that not same as str+=1
str is a pointer
added some more text, is it better? An array is not a pointer
in the book it does str+1
what will str+1 do anyways?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.