两个指针相减表示的意思是:两个地址在内存中间隔多少个指针类型的字节倍数
例如:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int *p = NULL;
int *q = NULL;
int n , m;
printf("Input two numbers n and m:");
scanf("%d%d",&n,&m);
p = &n;
q = &m;
printf("the address of n is: %d\n",&n);
printf("the address of m is: %d\n",&m);
printf("the length of it is: %d\n",p-q);
return 0;
}
实际上: (&n - &m)/sizeof(int) = p-q;
那么就可以理解函数返回值问题了!用自己编写的Strlen测字符串长度的函数来演示一下
int strlen1(char *s)
{
char *p = s;
while( *p )
{
p++;
}
return p-s;
}
这样的函数返回的实际上是字符串的长度,因为p指针指到字符串尾,存的是最后一位的地址,s指针指在数组首位,存的是第一位的地址!