Levis
Levis

Reputation: 23

C pointer problem: Why use *c instead of c?

I just started learning, I didn't understand the book, so I asked for advice. I am a beginner and don't have a good English. Function: Combine two two-digit positive integers A and B to form an integer in C Middle. The method of merging is: the ten digits and single digits of the A number are placed on the thousand and ten digits of the C number, and the ten and single digits of the B number are placed on the single and hundred digits of the C number. For example: when a=45, b=12. After calling this function, c=4251. Here is my code

#include <stdio.h> 
  
void fun(int a, int b, long *c);
 
int main()   
{ 
  int a,b;
  long c; 
  int state = 1;
  printf("Enter a: ");
  printf("(q to quit)");
 
  while( scanf("%d",&a)==state)
  {
    printf("Enter b: ");
    printf("(q to quit)");
    while( scanf("%d",&b)==state)
       {
          fun(a, b, &c);     
          printf("The result is: %ld\n", c);
 
       }
  }
  return 0;
}   
 
  void fun(int a, int b, long *c)     
{
  /**********Program**********/
    *c = 100*(a%100)+b%100;
  /**********  End  **********/
}

I tried removing the * and found that the result was 16. It is wrong but not know why

Upvotes: 0

Views: 92

Answers (1)

user9706
user9706

Reputation:

The parameter long *c means c is an address of a variable (in this case the variable in main() is called c and you need to call the function like this fun(a, b, &c)).

When you want to update the value stored at that address c the syntax is *c = .... If you do c = ... you are updating the address of the variable which has no external effect.

Alternatively, you could change your function to return a value and the call would then look like this:

   c = fun(a, b);

and the function would be:

int fun(int a, int b) {
    return 100*(a%100)+b%100;
}

Upvotes: 3

Related Questions