两个程序的疑惑
第一个:
#include<iostream.h>
struct stud
{
int no;
char name[10];
struct stud *next;
};
void fun(struct stud *s)
{
s=s->next;
}
void main()
{
int i;
struct stud s[2]={{1,"mary"},{2,"smith"}};
struct stud *h;
s[0].next=&s[1];
s[1].next=&s[0];
h=&s[0];
fun(h);
for (i=0;i<2;i++)
{
cout << h->name << ":" << h->no << " ";
h=h->next;
}
cout << endl;
}
第二个:
#include<iostream.h>
struct student
{
char *name;
double score;
};
int foud(struct student *,char *);
void main()
{ int a,i;
struct student data[3]={{"asd",98},{"yui",97},{"zxc",96}};
char *p="yui";
for(i=0;i<3;i++)
{
a=foud(&data[i],p);
if(a==1)
cout << data[i].name << ":" << data[i].score;
}
}
int foud(struct student *p,char *p1)
{
while(*p->name!='\0'&&*p1!='\0')
{
if(*p->name!=*p1)
return 0;
else
{
p->name++;
p1++;
}
}
return 1;
}
为什么第一个中的fun()函数没有影响到实参,而第二个中的fund()函数却影响到了实参
谁能讲讲原理
[解决办法]
本质上将,c++中的参数传递都是值拷贝的,即函数内部不能影响传入的参数本身。但是如果参数时指针或者引用(这两者本质都是指针)在函数内部就可以通过这个指针或者引用访问到其指向的对象,就可以间接修改对象。
第一个func中修改的s是一个对象的地址,没有对该地址的对象就行修改,当然不影响实参指向的对象的属性。
第二个更好相反
[解决办法]
很简单,呵呵,使用指针可以修改指针所指的内容,但是不能修改指针本身。
因此,其实p只是一个指针副本,只是与原指针指向同一个对象。
p = xxx,修改的是指针副本,是不起作用的;
*p = xxx,可以指针所指的对象,因为两个指针指向同一个对象。