【问题标题】:How to use two parameters pointing to the same structure in one function?如何在一个函数中使用指向同一结构的两个参数?
【发布时间】:2010-05-11 17:50:00
【问题描述】:

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

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

#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) 有何变化? 它在 main 中有何变化?

我知道我也应该声明test_2,像这样:

trial test,test_2;

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

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

那么请告诉我如何使用 test_2 作为指向与 test 相同结构的参数,都在同一个函数中..

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

【问题讨论】:

  • 我很困惑为什么你有一个函数需要两个指向同一个结构的参数......这听起来很奇怪。为什么需要这样做?
  • test_2 声明为struct trial 将创建一个新结构,而不是指向同一个结构。我怀疑你高度很困惑,你应该首先解释为什么你认为你首先需要这一切。
  • 我的程序需要两个矩阵文件然后显示它们,这个函数显示任何一个矩阵,两个矩阵的内容都保存在同一个结构中。
  • 那么你可能想做int trialtest( matrix_type m1, matrix_type m2);trialtest(test.m1, test.m2);吗?
  • @Jefromi,我更喜欢你提到的这种方式,但我被告知我不应该更改给定的原型函数.....

标签: c function structure declaration


【解决方案1】:

我认为这是你的作业,所以我将编写一个不同的函数,让你了解(我认为)你需要做什么。我读到您不想更改 trail_test 参数列表,所以我坚持使用类似的参数列表。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多