一.值传递
先来看普通变量的值传递,再来指针的值传递
普通变量值传递:
#include <stdio.h>
void swap(int m, int n)
{
int tmp;
tmp = m;
m = n;
n = tmp;
printf("m=%d, n=%d\n",m,n);
}
int main()
{
int a = 1, b = 2;
swap(a,b);
printf("a=%d, b=%d\n",a,b);
return 0;
}
输出:
普通变量的值传递,形参的修改并不会影响到实参。而且swap()函数调用完毕,m,n,tmp自动释放。
指针地址传递:
如果想通过函数来改变实参,必须地址传递。
利用指针来实现上面的a,b值互换。
#include <stdio.h>
void swap(int *m, int *n) // int *m 就是说定义一个指针 m和指针m
{
int tmp;
tmp = *m;
*m = *n;
*n = tmp;
printf("m=%d, n=%d\n",*m,*n);
}
int main()
{
int a = 1, b = 2;
swap(&a,&b); // int *m = &a,int *n = &b
printf("a=%d, b=%d\n",a,b);
return 0;
}
输出:
二.形参中的数组
#include <stdio.h>
void array_printf(int a[], int b)
{ //形参中的数组不是数组,而是指针变量
int i = 0;
for(i = 0; i < b; i++)
{
printf("%d, ",a[i]); //等价于*(a+i)
}
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(a)/sizeof(a[0]);
array_printf(a, n); //传递的是数组的首地址,还应该把数组元素个数传递过去,而不是把整个数组传过去,所以c语言快不是没道理的。
return 0;
}
三.字符串拷贝
#include <stdio.h>
int main()
{
char str[100];
char *p = str;
//strcpy()是给p所指向的内存拷贝内容,也就是拷贝给了str
//字符串可以不用*p,因为内部会处理
strcpy(p, "hello world");
printf("str = %s\n",str);
return 0;
}
拷贝功能函数实现:
#include <stdio.h>
void str_cpy(char *dst, char *src)
{
int i = 0;
while(src[i] != '\0')
{
dst[i] = src[i];
i++;
}
*(dst+i) = 0;
}
int main()
{
char src[] = "hello world";
char dst[100];
str_cpy(dst, src);
printf("dst = %s\n",dst);
return 0;
}