C语言里 用指针或者数组名做函数参数时,在被调用的函数体里 为什么有时候在参数或者指针前面加*有的不用

#include <stdio.h>
#define N 16
typedef struct
{ char num[10];
int s;
} STREC;
int fun( STREC *a, STREC *b )
{
int i,j=0,min=a[0].s;
for(i=0;i<N;i++)
if(min>a[i].s)
min=a[i].s; //为什么不加*
for(i=0;i<N;i++)
if(min==a[i].s)
b[j++]=a[i]; //为什么不加*
return j;

}
main()
{ STREC s[N]={{"GA05",85},{"GA03",76},{"GA02",69},{"GA04",85},
{"GA01",91},{"GA07",72},{"GA08",64},{"GA06",87},
{"GA015",85},{"GA013",91},{"GA012",64},{"GA014",91},
{"GA011",91},{"GA017",64},{"GA018",64},{"GA016",72}};
STREC h[N];
int i,n;FILE *out ;
n=fun( s,h );
printf("The %d lowest score :\n",n);
for(i=0;i<n; i++)
printf("%s %4d\n",h[i].num,h[i].s);
printf("\n");
out = fopen("out.dat","w") ;
fprintf(out, "%d\n",n);
for(i=0;i<n; i++)
fprintf(out, "%4d\n",h[i].s);
fclose(out);
}
第二个程序如下
#include <stdio.h>
void fun( char *a )
{

char *p=a;
while(*p=='*') p++;
for(;*p!='\0';p++,a++)
*a=*p; //这里为什么加*
*a='\0'; ////这里为什么加*

}
main()
{ char s[81];
void NONO ( );
printf("Enter a string:\n");gets(s);
fun( s );
printf("The string after deleted:\n");puts(s);
NONO();
}
void NONO()
{/* 本函数用于打开文件,输入数据,调用函数,输出数据,关闭文件。 */
FILE *in, *out ;
int i ; char s[81] ;
in = fopen("in.dat","r") ;
out = fopen("out.dat","w") ;
for(i = 0 ; i < 10 ; i++) {
fscanf(in, "%s", s) ;
fun(s) ;
fprintf(out, "%s\n", s) ;
}
fclose(in) ;
fclose(out) ;
}

第一个程序:a是指向结构体s[0]的指针,a[0]...a[i]就是第0-i个结构体,a[i].s表是结构体中s域;
a[i].s; (*(a+i)).s; (a+i)->s 3个的值是相等的;意思就是当定义一个结构体指针STREC *p_str后,把地址p_str起始的内容结构体化,同时(p_str+1)也是一个指向结构体类型STRECD的指针
其指向的地址为p_str的地址+sizeof(STREC)
sizeof(STREC) = 10(num[10])+2(为了对齐 凑成3*4)+4(int s) = 16byte
贴一段代码,在vc++6.0上跑的
#include <stdio.h>#include<stdlib.h>
typedef struct
{
char x[10];
int y;
}str;
void func(str *m,str *n);

void main()
{
str m[16]={{"GA05",85},{"GA03",76},{"GA02",69},{"GA04",85},
{"GA01",91},{"GA07",72},{"GA08",64},{"GA06",87},
{"GA015",85},{"GA013",91},{"GA012",64},{"GA014",91},
{"GA011",91},{"GA017",64},{"GA018",64},{"GA016",72}};
str *n;

n = (str *)(&m); //&m为一个void型指针,(str *)将其强制类型转换
func(m,n);
system("pause");
}

void func(str *m,str *n)
{
int i;
for(i=0; i<16; i++)
{
printf("%d ",m[i].y);
printf("%d ",(*(m+i)).y);
printf("%d\n",(m+i)->y);
}
printf("%x",n);
printf("%x",n+1);
}

第二个程序
a是指向s[0]的指针,你的意图应该是给数组s[81]赋值;显然*(a+i) == s[i];
*(a+i)也能写成a[i];追问

你的意思是在第二个程序里,*(a+i)与a[i]是等价可以互换的???

追答

a是指针,可以写成a[i],只是可以写成a[i],a依然是指针,a[i]看起来比较直观

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-09-21
为什么要加*,一个是指针,一个是数组,消息来自华夏联盟
相似回答