Re: compiling error
- From: Kapteyn's Star <remove_digits_for_email_7Kapteyns3.Star@xxxxxxxxxxxxx>
- Date: Tue, 15 Jul 2008 15:10:57 +0200 (CEST)
Richard Heathfield writes:
Kapteyn's Star said:
Hi newsgroup
The program here given is refused by GCC with a error i cannot
understand. It says
rnd00.c: In function ?main?:
rnd00.c:26: error: expected expression before ?]? token
How to make it compile? I also tried buf[10] but that gives
"segmentation fault". Thanks in advanced.
/* scanf 10 random integers from /dev/random */ #include <stdio.h>
void open_file(FILE *f)
{
f= fopen("/dev/random", "r");
This won't do what you think. If you want a function to change the value
of an object, you must pass to that function the address of the object.
Alternatively, you can get the function to return the new value of the
object, and pick it up in the caller, as shown:
FILE *open_file()
{
return fopen("/dev/random", "r");
}
usage: fp = open_file();
If you want to do it the parameter way, you need to do this:
void open_file(FILE **f)
{
*f = fopen("/dev/random", "r");
}
Usage: open_file(&fp);
oops I forget constantly that C does pass by value for functions, curse
of having learned Pascal in school :)
Remember that fopen will return a null pointer if it fails to open the
file.
Okay. I ommited checking fopen() because /dev/random exists here. But i
see your point, it might be absent under older kernels.
}
void read_values(FILE *f, int buf[], int count) {
do
{
--count;
fread((void*)&buf[count], sizeof(int), 1, f);
Simpler:
fread(&buf[count], sizeof buf[count], 1, f);
I thought that a typecast is needed when converting between different
typed pointers...
or even
fread(buf + count, sizeof buf[count], 1, f);
This is neat! I still not getting the hang of pointer arithmetics. :(
But sizeof without parenthesis just feels weird. I thought it wont
compile but it does! So much to learn in c...
<snip>
int main()
{
int buf[10];
int count= 10;
FILE *f;
open_file(f);
read_values(f, buf[], count);
This should be: read_values(f, buf, count);
Okay arrays when passed to function should not have the index but the
index is needed when in the prototype? Noted.
Thanx to you and Ben... program works now!
--
Kapteyn's Star
.
- Follow-Ups:
- Re: compiling error
- From: Richard Heathfield
- Re: compiling error
- References:
- compiling error
- From: Kapteyn's Star
- Re: compiling error
- From: Richard Heathfield
- compiling error
- Prev by Date: Re: doubles and ints
- Next by Date: Re: compiling error
- Previous by thread: Re: compiling error
- Next by thread: Re: compiling error
- Index(es):
Relevant Pages
|