关键词搜索

源码搜索 ×
×

浅谈数组名作形参

发布2014-04-08浏览10731次

详情内容

       首先,要说明的是,以下三个函数完完全全等价:

 

  1. void fun(char *str)
  2. {
  3. }
  1. void fun(char str[])
  2. {
  3. }
  1. void fun(char str[10000])
  2. {
  3. }

    

 

     好,看看下面这个程序应该怎么改:

 

  1. #include <iostream>
  2. using namespace std;
  3. void fun(char *str)
  4. {
  5. char s[] = "abcdefg";
  6. str = s;
  7. }
  8. int main()
  9. {
  10. char str[] = "1234567";
  11. fun(str);
  12. cout << str << endl;
  13. return 0;
  14. }


     应该改为:

 

 

  1. #include <iostream>
  2. using namespace std;
  3. void fun(char *str, int n)
  4. {
  5. char s[] = "abcdefg";
  6. strncpy(str, s, n);
  7. *(str + n) = '\0'; //最好加上这一句,防止main中的str没有初始化
  8. }
  9. int main()
  10. {
  11. char str[8];
  12. fun(str, 7);
  13. cout << str << endl;
  14. return 0;
  15. }


      可见,当字符数组str作为形参时, 如果在fun中要改变str指向的值, 强烈建议加上字符串的长度(不加也可以,在被调函数中可以用strlen求出字符串的长度, 千万不能用sizeof)。如果在fun中,仅仅用str指向的串,不改变它,那么,可以不传长度。

 

 

      但是,如果是整形数组,无论是否改变数组指针指向的值,都必须传长度,因为在被掉函数中,无法求出数组的长度

  1. #include <iostream>
  2. using namespace std;
  3. void fun(int *a, int n)
  4. {
  5. int i = 0;
  6. for(i = 0; i < n; i++)
  7. {
  8. cout << *(a + i) << endl;
  9. }
  10. }
  11. int main()
  12. {
  13. int a[] = {1, 2};
  14. int n = sizeof(a) / sizeof(a[0]); // 不能放在fun中
  15. fun(a, n);
  16. return 0;
  17. }

 

  1. #include <iostream>
  2. using namespace std;
  3. void fun(int *a, int n)
  4. {
  5. int i = 0;
  6. for(i = 0; i < n; i++)
  7. {
  8. *(a + i) *= 10;
  9. }
  10. }
  11. int main()
  12. {
  13. int a[] = {1, 2};
  14. int n = sizeof(a) / sizeof(a[0]); // 不能放在fun中
  15. fun(a, n);
  16. int i = 0;
  17. for(i = 0; i < n; i++)
  18. {
  19. cout << *(a + i) << endl;
  20. }
  21. return 0;
  22. }


       睡觉。

    

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载