如何解决交换结构数组元素
我很难在结构体中应用引用传递和值传递分离。如何交换固定大小结构数组的元素,如下所示。
struct try{
int num;
char name[10];
};
int main(){
struct try book[3];
void swapper(/********/);// <-what should be the argument of this function
}
void swapper(/********/){//swap second and third element of struct array
/*how the swap may be done?
temp=book[2];
book[2]=book[3];
temp=book[3];*/
}
解决方法
有很多方法可以满足您的要求。一种方法:
#include <stdio.h>
struct try {
int num;
char name[10];
};
void
swapper(struct try *a,int b,int c)
{
struct try tmp = a[b];
a[b] = a[c];
a[c] = tmp;
}
void
display(const struct try *t,size_t count)
{
while( count-- ){
printf("%d: %s\n",t->num,t->name);
t += 1;
}
}
int
main(void) {
struct try book[] = {
{ 1,"foo"},{ 2,"bar"},{ 3,"baz"}
};
display(book,sizeof book / sizeof *book);
swapper(book,1,2);
display(book,sizeof book / sizeof *book);
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。