再看看下边程序
											#include "stdio.h"
f(char *s)
{char *p=s;
while ( *p!='\0') p++;
return (p-s);
}
main()
{
printf("result:%d\n",f("GHEDG"));
}
答案为什么会是5呢?程序是怎么运行的啊?有请网友帮助并详细给解释下。
#include "stdio.h"
f(char *s)
{char *p=s;
while ( *p!='\0') p++;
return (p-s);
}
main()
{
printf("result:%d\n",f("GHEDG"));
}
答案为什么会是5呢?程序是怎么运行的啊?有请网友帮助并详细给解释下。
 2007-03-15 13:18
	    2007-03-15 13:18
   2007-03-15 13:21
	    2007-03-15 13:21
   2007-03-15 13:27
	    2007-03-15 13:27
  
 2007-03-15 13:28
	    2007-03-15 13:28
   2007-03-15 13:30
	    2007-03-15 13:30
   2007-03-15 13:46
	    2007-03-15 13:46
   2007-03-15 13:50
	    2007-03-15 13:50
  并不是你所说的那样,因为p++ 自加的是一个相对的值,
而p-s 不是纯地址的相减,而是一个相对的位置相减,
如果把上述的char 改为int 型还是一样的结果.
举一个例子.
#include <stdio.h>
#include <conio.h>
int fun(int *string)
{
        int *p=string;
        while(*p!=1)
                p++;
        return (p-string);
}
main()
{
        int string[5]={5,4,3,2,1};
        clrscr();
        printf("%d",fun(string));
        getch();
}										

 2007-03-15 14:27
	    2007-03-15 14:27
   2007-03-15 14:35
	    2007-03-15 14:35