tags:

views:

31

answers:

2

Hello,

I have a structure in my program that contains a particular array. I want to scan a random file with numbers and put the contents into that array.

This is my code : ( NOTE : This is a sample from a bigger program, so I need the structure and arrays as declared )

The contents of the file are basically : 5 4 3 2 5 3 4 2

#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;
  FILE *fin;
  fin=fopen("randomfile.txt","r"); 
  for(i=0;i<5;i++){
      fscanf(fin,"%5.2f\t",(*test).what[z][x]);
    }
  fclose(fin);
  return 0;
}

But the problem is, whenever this I run this code, I get this error : alt text

(25) : warning 508 - Data of type 'double' supplied where a pointer is required

I tried adding

do{
   for(i=0;i<5;i++){
      q=fscanf(fin,"%5.2f\t",(*test).what[z][x]);
    }
  }while(q!=EOF);

But that didnt work either, it gives the same error.

Does anyone have a solution to this problem ?

A: 

This expression: (*test).what[z][x] is a float in the array (which gets promoted to a double, thus the warning message). fscanf() needs to get a pointer to the data (in this case a float), so that it can write to it. You need to change this line to:

q=fscanf(fin,"%5.2f\t",&(*test).what[z][x]);

As a side note, accessing the member of a struct through a pointer to that struct is so common that you have a special -> operator in C to do just that. So instead of (*foo).bar you can write foo->bar.

So the line becomes a slightly more readable:

q=fscanf(fin,"%5.2f\t",&test->what[z][x]);
slacker
Voted best since its more informative, thank you both guys :)
ZaZu
A: 

Looks like you're trying to read the value of what[z][x] instead of referencing it:

fscanf(fin,"%5.2f\t",(*test).what[z][x]);

Try this:

fscanf(fin,"%5.2f\t",&((*test).what[z][x]));

Or,

fscanf(fin,"%5.2f\t",&(test->what[z][x]));
amphetamachine
slacker
Such a simple error that I couldnt figure out . Thank you thank you thank you :)
ZaZu