C语言修改地址内容的值传递

C语言—修改地址内容的值传递(一)

这是我第一次写博客,这一次写博客是因为我在为二级C语言考试做准备时,发现了一个我搞不懂得题目,题目如下:

  • 题目 :下列给定程序中函数fun的功能是:将长整型数中各位上为奇数的数依次取出,构成一个新数放在t中。高位仍在高位,低位仍在低位。
    例如,当s中的数为87653142时,t中的数为7531。
    请改正程序中的错误,使它能得出正确的结果。
#include <stdio.h>
void fun (long  s, long *t)
{     int   d;
      long  sl=1;
/************found************/
      t = 0;
    while ( s > 0)
    {    d = s%10;
/************found************/
         if (d%2 == 0)
         {      
            *t = d * sl + *t;
            sl *= 10;
         }
         s /= 10;
    }
}
main()
{  long s, t;
   printf("\nPlease enter s:"); 
   scanf("%ld", &s);
   fun(s, &t);
   printf("The result is: %ld\n", t);
}
  • 有函数定义可知,变量t是指针变量,所以对t进行赋值0是不对的。因为t指向的是存放新数的变量,所以此处应给新数赋初值0,既*t=0。
  • 变量d表示数s各个位上的数, 此处的if条件应为判断d是否为奇数
    答案:
#include <stdio.h>

void fun (long  s, long *t)
{ int   d;
  long  sl=1;
/************found************/
  *t = 0;
  while ( s > 0)
  {  d = s%10;
/************found************/
     if (d%2!= 0)
     {  *t = d * sl + *t;
    sl *= 10;
     }
     s /= 10;
  }
}
main()
{  long s, t;
   printf("\nPlease enter s:"); scanf("%ld", &s);
   fun(s, &t);
   printf("The result is: %ld\n", t);
}

运行结果:
运行结果

main函数中的printf 当中t的值究竟来自于哪里?main函数中没有对t的操作,为什么t的值发生了改变?fun函数中t的作用是什么?

  • void fun (long s, long *t)中的t,是将变量t的内存地址传入函数中,在函数中对t进行内存内容的操作。函数fun中对t的操作,实际上操作的是t所指向的内存空间,即t的值。在函数中修改了t内存中的数值,所以当函数结束没有返回值,但是t的值发生了改变
/*
函数fun无返回值得原因是因为:程序直接对t的地址空间进行操作,直接改变t地址空间的内容实现内容地传递

等价于:
long fun (long  s) 
{ int   d;
  long  sl=1,t = 0;         
  while ( s > 0)
  {  d = s%10;
     if (d%2 = 0)
     {  
        t = d * sl + t;
        sl *= 10;
     }
     s /= 10;
  }
  return t;
}

*/

#include <stdio.h>

void fun (long  s, long *t) 
{ int   d;
  long  sl=1;
  *t = 0;           //3,将变量t内存空间的内容变为0
  while ( s > 0)
  {  d = s%10;
     if (d%2 = 0)
     {  
        *t = d * sl + *t;//4,累加得到答案
        sl *= 10;
     }
     s /= 10;
  }
}

main()
{  long s, t;       // 1,定义一个变量t,以后对他的内存空间直接进行操作
   printf("\nPlease enter s:"); 
   scanf("%ld", &s);
   fun(s, &t);      //2,将变量t的内存地址传入函数中
   printf("The result is: %ld\n", t);
}


这是我写的第一个博客,有什么不足请多多指教

猜你喜欢

转载自blog.csdn.net/qq_35133320/article/details/52578305