【问题标题】:Swapping struct array elements交换结构数组元素
【发布时间】:2021-08-07 05:09:43
【问题描述】:

我很难在结构中应用按引用传递和按值分隔传递。如何交换固定大小的结构数组的元素,如下所示。

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];*/

  }

【问题讨论】:

  • 这是c还是c++? C只支持指针传递,不支持引用。你的语法也是错误的。 'try' 这个词在 c++ 中是保留的,你在 main 中对 swapper 的调用不是调用而是前向声明。
  • 它在 C @StewartSmith 中。你能用一个例子解释更多吗,我在网上没有找到一个合适的例子..
  • @StewartSmith:“按引用传递”是一个通用编程术语,并不特定于 C++ 引用。仅在 C++ 中是特定于 C++ 引用的术语。在 C 中,它相当于“通过指针传递”。另外,由于问题被标记为“c”,所以使用标识符名称try没有任何问题。
  • 请注意,尝试读取具有 3 个元素的数组的 book[3] 是未定义的。对于struct try book[3],有效索引为 0、1 和 2。
  • 我错了@WilliamPursell。我应该编辑这个问题吗?

标签: c pass-by-reference swap pass-by-value


【解决方案1】:

有很多方法可以满足您的要求。一种方法:

#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;
}

【讨论】:

  • 非常感谢您的回答,最后以main中初始化struct为例有什么特殊原因吗?
  • 读取未初始化的数据是未定义的行为,因此对于示例数据必须进行初始化。这样做似乎最简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 2010-10-26
  • 1970-01-01
相关资源
最近更新 更多