Reputation: 2148
Very simple script throw this error :
passing argument 1 of ‘fprintf’ makes pointer from integer without a cast
Why is that ? The code is :
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *FP;
if((FP = fopen("file.txt", "r+")) == NULL) {
printf("File won't open\n");
return(1);
}
foo(FP);
return(0);
}
int foo(FP) {
char name[31];
printf( "Please enter a name (within 30 char) : \n");
gets(name);
fprintf(FP, "%s\n", name);
return(0);
}
Upvotes: 0
Views: 4466
Reputation: 424
You forgot the type classifier in FP parameter in the Foo function. Surprisingly you didn´t get an warning about it.
when you are compiling, please turn on the -Wall
and -pedantic
flag (if you are on gcc
). or at least the -Wimplicit-int
warning flag to avoid similar problems
Upvotes: 0
Reputation: 16026
The parameter FP in the declaration of foo(FP)
has no type which makes it default to int
. Because foo
uses it as the first parameter in a call to fprintf
, the int gets converted to a FILE
pointer which is legal but deprecated.
Fix: Simply declare foo
as int foo(FILE *FP){...}
.
Edit: And yes, as LPs said, you should declare the function before use, especially if you pass or return other types than int to or from it. The declaration can either be separate from the definition, possibly in a header; or you simply move the function definition, which is also a declaration, to a place before its first use.
Upvotes: 1
Reputation: 93
By default the function arg in C has type int. So when you define your function the signature actually is
int foo(int FP).
You should change it to
int foo(FILE *FP)
And, of course, it would be nice to declare function before call it.
Upvotes: 1
Reputation: 16223
Change
int foo(FP) {
to
int foo(FILE * FP) {
You must put a prototype of foo
function at the top of your code.
Upvotes: 2