0

I am trying to find the number of digits in a given number through the use of pointers.

This code below will give the correct output,

void numDigits(int num, int *result) {
  *result = 0;

  do {
    *result += 1;
    num = num / 10;
  } while (num > 0);
}

However, if I change the *result += 1; line to *result++;, the output will no longer be correct and only give 0.

What is going on here?

2
  • Check this will helps, stackoverflow.com/questions/1068849/… Commented Oct 14, 2020 at 6:46
  • 1
    Do you mean (*result)++or *(result++)? Commented Oct 14, 2020 at 6:47

3 Answers 3

2

In C/C++, precedence of Prefix ++ (or Prefix --) has higher priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix --) is higher than both Prefix ++ and *.

If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right associative).

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

Comments

1

*result++ is interpreted as *(result++).

Comments

0

the order of evaluation is the increment is first, then you dereference the pointer, the value of the pointer stays the same for the line in the expression if it's a postfix. what you are trying to do is to increment the dereference of the pointer so you need to put the parenthesis on the dereference then increment it, like this: (*result)++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.