-1

I'm doing an assignment for my into to programming in C class using arrays, using fscanf to take integers from a file and then print them. The code will build, but when I run it the program stops working during the Display function on line 31. The error it gives is "exception thrown at 0x00CE50F1 in Project 6.exe: 0xC0000005: Access violation writing location 0x00F4D720." I'm sure im doing something wrong with arrays, as my professor has the array written like "array[count]" not "array[&count]" when printing and scanning, but if I write it like that visual studio underlines "count" and says "expression must have pointer-to-object type". I'm not trying to cheat, i'd like to know what's wrong and how I can make it work.

   #define CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int Greeting();
void Display(numchosen, Numptr, array);

int main() {
    int numchosen, array[20];
    FILE * Numptr;

    Numptr = fopen("numInput.txt", "r");
    numchosen = Greeting();
    Display(numchosen, &array, Numptr);
}

int Greeting() {
    int numchosen;

    printf("How many integers should I retreive from the file? (1-20)\n");
    scanf("%d", &numchosen);

    return numchosen;
}
void Display(numchosen, array, Numptr) {
    int numprinted, numnum = 1, currentnum, count=0;


    for (numprinted = 0; numprinted < numchosen; numprinted++) {


        fscanf(Numptr, "%d", &array[&count]);
        printf("%d. %d\n", numnum, array[&count]);

        numnum ++;
        count++;
    }
}
Casey
  • 5
  • 2
  • It seem you need to take a few steps back, [get a couple of good beginners books](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list), and start over. Any modern (since the last 30 years or so) compiler should have emitted *tons* of warnings. – Some programmer dude Nov 05 '17 at 23:51
  • 1) `void Display(numchosen, array, Numptr)` --> `void Display(int numchosen, int array[], FILE *Numptr)` 2) `fscanf(Numptr, "%d", &array[&count]);` --> `fscanf(Numptr, "%d", &array[count]);` 3) `printf("%d. %d\n", numnum, array[&count]);` --> `printf("%d. %d\n", numnum, array[count]);` – BLUEPIXY Nov 05 '17 at 23:58
  • @BLUEPIXY You missed one, using `&array` when passing the array. Sure it will point to the correct location, but there's is a semantic mismatch. – Some programmer dude Nov 06 '17 at 00:01
  • @Someprogrammerdude I agree. 4) `Display(numchosen, &array, Numptr);` --> `Display(numchosen, array, Numptr);` – BLUEPIXY Nov 06 '17 at 00:02

1 Answers1

0

Declare your argument types!

void Display(numchosen, array, Numptr)

shoud read

void Display(int numchosen, int *array, FILE * Numptr)

Watch your types!

    fscanf(Numptr, "%d", &array[&count]);
    printf("%d. %d\n", numnum, array[&count]);

Never index by the address of something. That's a type mismatch.

    fscanf(Numptr, "%d", &array[count]);
    printf("%d. %d\n", numnum, array[count]);

This looks right.

Joshua
  • 40,822
  • 8
  • 72
  • 132