首先,要说明的是,以下三个函数完完全全等价:
- void fun(char *str)
- {
-
- }
- void fun(char str[])
- {
-
- }
- void fun(char str[10000])
- {
-
- }
好,看看下面这个程序应该怎么改:
- #include <iostream>
- using namespace std;
-
- void fun(char *str)
- {
- char s[] = "abcdefg";
- str = s;
- }
-
- int main()
- {
- char str[] = "1234567";
- fun(str);
- cout << str << endl;
- return 0;
- }
应该改为:
- #include <iostream>
- using namespace std;
-
- void fun(char *str, int n)
- {
- char s[] = "abcdefg";
- strncpy(str, s, n);
- *(str + n) = '\0'; //最好加上这一句,防止main中的str没有初始化
- }
-
- int main()
- {
- char str[8];
- fun(str, 7);
- cout << str << endl;
- return 0;
- }
可见,当字符数组str作为形参时, 如果在fun中要改变str指向的值, 强烈建议加上字符串的长度(不加也可以,在被调函数中可以用strlen求出字符串的长度, 千万不能用sizeof)。如果在fun中,仅仅用str指向的串,不改变它,那么,可以不传长度。
但是,如果是整形数组,无论是否改变数组指针指向的值,都必须传长度,因为在被掉函数中,无法求出数组的长度
- #include <iostream>
- using namespace std;
-
- void fun(int *a, int n)
- {
- int i = 0;
- for(i = 0; i < n; i++)
- {
- cout << *(a + i) << endl;
- }
- }
-
- int main()
- {
- int a[] = {1, 2};
- int n = sizeof(a) / sizeof(a[0]); // 不能放在fun中
- fun(a, n);
-
- return 0;
- }
- #include <iostream>
- using namespace std;
-
- void fun(int *a, int n)
- {
- int i = 0;
- for(i = 0; i < n; i++)
- {
- *(a + i) *= 10;
- }
- }
-
- int main()
- {
- int a[] = {1, 2};
- int n = sizeof(a) / sizeof(a[0]); // 不能放在fun中
- fun(a, n);
-
- int i = 0;
- for(i = 0; i < n; i++)
- {
- cout << *(a + i) << endl;
- }
-
- return 0;
- }
睡觉。