The printf("%n", numberOfIntegers)
call will write a zero into the integer pointed to by numberOfIntegers
. That's because there are zero characters written before the %n
format is interpreted (see the specification for printf()
).
Probably, you wanted to use:
printf("%d\n", *numberOfIntegers);
An SSCCE
Here is an SSCCE (Short, Self-Contained, Correct Example) closely based on the code shown in the question that demonstrates that there is nothing horribly wrong with that code — and hence that the problems encountered in the question are in code that is not shown.
#include <stdio.h>
static
int *readIntegers(const char *filename, int *numberOfIntegers)
{
FILE *fp = fopen(filename, "r");
int count;
if (fp == NULL)
{
return NULL;
}
while (fscanf(fp, "%d", &count) > 0)
{
(*numberOfIntegers)++;
}
printf("%d\n", *numberOfIntegers);
fclose(fp);
return numberOfIntegers;
}
int main(int argc, char **argv)
{
const char *file = "data";
int num = 0;
int *p;
if (argc > 1)
file = argv[1];
p = readIntegers(file, &num);
if (p != &num)
{
fprintf(stderr, "Failed to read numbers from file %s\n", file);
return 1;
}
else
printf("Number of numbers in file %s is %d\n", file, num);
return 0;
}
Given a file called data
containing:
0 1 2 3 4 5 6 7 8 9 10
Or the equivalent file with each blank replaced by a newline, the output of the program is:
11
Number of numbers in file data is 11
If the program is called ri
(Read Integers), and is called as:
$ ./ri missing
Failed to read numbers from file missing
$
In neither case does it crash. I added the code to close the file and return the input pointer. This code compiles cleanly on Mac OS X 10.8.4 using GCC 4.8.1 with the command line set to extremely stringent:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
> -Wold-style-definition ri.c -o ri
$
So, as stated, the problem is not directly in the code fragment presented to us for scrutiny.
The compiler warnings that you are ignoring really worry me precisely because they point to problems that will manifest themselves after the code shown successfully executes. Returning a pointer to a local variable is a way to crash programs; returning the wrong type of pointer from a function is a way to crash programs. (I'll grant you that the unused variable warning is about as benign as they get — I am not worried about that one, though by commenting out the declaration, you've prevented it from appearing.)
So, you need to present more program for anyone to diagnose successfully your problem. What you show is OK code.