簡體   English   中英

傳遞struct成員以在c中起作用

[英]passing struct member to function in c

我有此文件,並將其輸入為c中的struct數組。 但是我在將struct成員傳遞給函數時遇到問題。 錯誤:第58行的下標甚至都沒有指針或數組值。我是c的新手,並且這個問題堅持了一周。

代碼:

#include <stdio.h>
#include <math.h>
#define SIZE 100

typedef struct list{
  int counter;
  int year;
  double maxrain;
  double rank;
} data;

double avg (struct list s, int count);

int main()
{
  data a[SIZE];
  struct list s;
  double sum = 0;
  int totalFile = 1;        // according to number of csv file
  int z, i;
  char fName[16];
  FILE*fpt;

  double mean;

  /* reading multiple file */
  for (z=1; z<=totalFile; z++)
  {
    sprintf(fName," ",z);
    fpt = fopen(fName,"r");

    if(fpt == NULL){
      printf("Error opening %s\n",fName);
      return(-1);
    }

    printf("---Reading from file %d---\n", z);
    sum = 0;
    i = 0;
    while(i <= SIZE && fscanf(fpt, "%d%*c%d%*c%f%*c%f", &a[i].counter, &a[i].year, &a[i].maxrain, &a[i].rank) != EOF){
      sum = sum + a[i].maxrain;
      i++;  
    }
    mean = avg(a[i].maxrain, i);
    printf("%f", mean);

    return 0;
  }
}

double avg(struct list s , int count)
{
  double ave;
  int i = 0;

  for(i=0; i<count; add += s.maxrain[i++]);
  ave = add/count;

  return ave;
}

如果您已告訴編譯器告訴您可能出現的警告的最大值,則編譯器將在此處指出幾個問題。 對於gcc,這樣做的選項是-Wall -Wextra -pedantic

但現在就這些問題進行詳細介紹:

這里

sprintf(fName, " ", z);

缺少轉換說明符。 該代碼應如下所示:

sprintf(fName, "%d", z);

sprintf()也未保存,因為它可能會溢出目標“字符串”。 使用snprintf()代替:

snprintf(fName, "%d", sizeof(fName), z);

下面的掃描命令使用%f ,它預期為float,但有double傳入。

fscanf(fpt, "%d%*c%d%*c%f%*c%f", &a[i].counter, &a[i].year, &a[i].maxrain, &a[i].rank)

使用%lf掃描雙打:

fscanf(fpt, "%d%*c%d%*c%lf%*c%lf", &a[i].counter, &a[i].year, &a[i].maxrain, &a[i].rank)

這個

mean = avg(a[i].maxrain, i);

應該

mean = avg(a[i], i);

最后, avg()缺少add的聲明/定義。


作為向服務器聲明變量作為數組索引的注釋:

數組索引始終為正,因此為此使用帶符號變量沒有意義。

同樣也不確定一個或另一種整數類型的寬度,因此使用每個地址尋址存儲器都將是不節省的。 要在尋址數組元素(以及使用此內存)時保留在保存側,請使用size_t ,C標准保證它是一個無符號整數,寬度足以尋址所有機器內存(並使用最大可能的數組元素) 。

1.將struct的元素傳遞給函數:

main() {
    struct list data = {1, 2, 3, 4};
    avg(data.counter, data.year, data.maxrain, data.rank, 5);
}

double avg(int counter, int year, double maxrain, double rank, int count) {
    //    
}

2.將結構傳遞給函數

main() {
    struct list data = {1, 2, 3, 4};
    avg(data, 5);
}

double avg(struct list s , int count) {
    //    
}

3.用指針將結構的地址傳遞給函數

main() {
    struct list data = {1, 2, 3, 4};
    avg(&data, 5);
}

double avg(struct list *s , int count) {
    //    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM