代码之家  ›  专栏  ›  技术社区  ›  NLed

如何在一个函数中使用指向同一结构的两个参数?

  •  0
  • NLed  · 技术社区  · 14 年前

    下面的代码由一个结构、一个主函数和一个函数组成。函数应该显示两个具有特定值的参数,这两个参数都指向相同的结构。

    我不知道如何将第二个参数添加到以下代码中的问题:

    #include<stdio.h>
    
    #define first 500
    #define sec 500
    
    
    struct trial{
      int f;
      int r;
      float what[first][sec];
    };
    
    int trialtest(trial *test);
    
    main(){
      trial test;
      trialtest(&test);
    }
    
    int trialtest(trial *test){
      int z,x,i;
      for(i=0;i<5;i++){
          printf("%f,(*test).what[z][x]);
        }
      return 0;
    }
    

    我需要添加一个新参数 test_2 这里(在同一个函数中)使用此代码:

      for(i=0;i<5;i++){
          printf("%f,(*test_2).what[z][x]);
    

    如何 int trialtest(trial *test) 变化? 它主要是如何变化的?

    我知道我应该申报 试验2 还有,像这样:

    trial test,test_2;
    

    但是在函数中传递地址呢?我不需要编辑它,对吗?

      trialtest(&test); --- This will remain the same ?
    

    因此,请告诉我如何使用test_2作为参数,指向与test相同的结构,这两个结构都在相同的函数中。

    谢谢您!! 如果你需要更多的说明,请告诉我

    1 回复  |  直到 14 年前
        1
  •  1
  •   nategoose    14 年前

    我认为这是你的家庭作业,所以我会写一个不同的函数,让你知道你需要做什么。我听说你不想更改trail_测试参数列表,所以我坚持使用类似的参数列表。

    struct thing {
       /* put some stuff here */
    };
    typedef struct thing thing; /* because this is C, not C++ */
    
    int how_many_things(thing * thing_list);
    
    int main(void) {
         int i;
         thing * a;
         int count_init = random(); /* let's surprise ourselves and make a random number of these */
         count_init %= 128; /* but not too many or it might not work at all */
    
         a = malloc(count_init*sizeof(things)+1);
         for (i = 0; i < count_init; i++) {
             thing_init(&(a[i]));
         }
         make_illegal_thing(&(a[count_init]) ); /* like '\0' at the end of a string */
    
         printf("There are %i things in the list\n", how_many_things(a) );
    
         return 0;
    }
    
    /* This is very similar to strlen */
    int how_many_things(thing * a) {
        int count = 0;
        while (is_legal_thing(a) ) {
            a++;
            count++;
        }
        return count;
    }