【问题标题】:C pointer problem: Why use *c instead of c?C指针问题:为什么用*c而不是c?
【发布时间】:2023-02-04 13:56:27
【问题描述】:

刚开始学习,书上看不懂,求教。 我是初学者,英语不好。 功能:将两个两位数的正整数A和B组合成C中的一个整数 中间。合并的方法是:A号的十位和个位数放在C号的千位和十位上,B号的十位和个位放在C号的个位和百位上数字。 例如:当a=45时,b=12。调用此函数后,c=4251。这是我的代码

#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  **********/
}

我试着去掉*,发现结果是16。这是错误的,但不知道为什么

【问题讨论】:

    标签: c


    【解决方案1】:

    参数long *c表示c是一个变量的地址(这里也称为c),如果要更新存储在该地址的值,语法为*c = ...。如果你这样做c = ...,你正在更新没有外部影响的变量的地址。或者,您可以更改函数以返回一个值,然后调用将如下所示:

       c = fun(a, b);
    

    功能是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2021-11-02
      • 2010-11-15
      • 2011-08-02
      • 2011-04-15
      • 1970-01-01
      相关资源
      最近更新 更多