Search code examples
cdynamic-memory-allocationdynamic-struct

Unable to write to memory after passing dynamic structure in C


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define FLUSH myFlush()

struct testInfo {
    int grade;
    char letterGrade;
    char student[30];
};

void menuPrint(int);
void enterScores(struct testInfo **scores, int size);
void printScores(struct testInfo scores[], int size);
char getChoice();
void myFlush();

int main(void) {
    struct testInfo *testScores = { 0 };
    char userChoice;
    int size = 0;
    do {
        system("clear");
        menuPrint(1);
        userChoice = getChoice();
        switch (userChoice) {
        case 'e': case 'E':
            system("clear");
            menuPrint(2);
            printf("Please enter the number of test scores: ");
            scanf_s("%d", &size); FLUSH;
            testScores = (struct testInfo*)malloc(size * sizeof(struct testInfo));
            if (!testScores) { //if there is an error in allocating the memory, exits program.
                printf("\nA problem has occured with malloc.");
                exit(EXIT_FAILURE);
            }
            else {
                enterScores(&testScores, size);
            }
            system("pause");
            break;
        case 'p': case 'P':
            printScores(testScores, size);
            system("pause");
            free(testScores);
            break;
        case 'l': case 'L':
            system("pause");
            break;
        }
    } while (userChoice != 'l' && userChoice != 'L');
    return 0;
}//end main

I am trying to pass a dynamic structure to a function so the user can write the student's name and test score they got on a test. I've used Passing a Structure by reference to a function that will dynamically create and fill a array of structures as a reference to figure out how to pass the dynamic structure to the function, but when the user starts inputting, I can get through 1 loop before an exception is thrown saying "Access violation writing".

void enterScores(struct testInfo **scores, int size) {
    int i;
    char name[30];

    for (i = 0; i < size; i++) {
        printf("\nEnter student's name: ");
        fgets(name, 30, stdin);
        strcpy(scores[i]->student, name);
        printf("\nEnter test score: ");
        scanf_s("%i", &scores[i]->grade);
        while (scores[i]->grade < 0 || scores[i]->grade > 120) {
            printf("\nError in grade range (0-120), try again.");
            printf("\nEnter test score: ");
        }
        //determines letter grade from test Score
        if (scores[i]->grade > 90) {
            scores[i]->letterGrade = 'A';
        }
        if (scores[i]->grade < 90 && scores[i]->grade >= 80) {
            scores[i]->letterGrade = 'B';
        }
        if (scores[i]->grade < 80 && scores[i]->grade >= 70) {
            scores[i]->letterGrade = 'C';
        }
        if (scores[i]->grade < 70 && scores[i]->grade >= 60) {
            scores[i]->letterGrade = 'D';
        }
        if (scores[i]->grade < 60 && scores[i]->grade >= 0) {
            scores[i]->letterGrade = 'F';
        }
    }
}//end enterScores

Solution

  • Your current enterScores is accepting an array of pointers to struct testInfo, but what is actually passed is a pointer to single pointer to struct testInfo. This is treated as one-element array, and therefore accessing scores[1] and further is invalid.

    What you want seems:

    Declaration of the function:

    void enterScores(struct testInfo scores[], int size);
    

    (use the same scheme as printScores)

    Call of the function:

                    enterScores(testScores, size);
    

    (remove &)

    Definition of the function:

    void enterScores(struct testInfo scores[], int size) {
        int i;
        char name[30];
    
        for (i = 0; i < size; i++) {
            printf("\nEnter student's name: ");
            fgets(name, 30, stdin);
            strcpy(scores[i].student, name);
            printf("\nEnter test score: ");
            scanf_s("%i", &scores[i].grade);
            while (scores[i].grade < 0 || scores[i].grade > 120) {
                printf("\nError in grade range (0-120), try again.");
                printf("\nEnter test score: ");
            }
            //determines letter grade from test Score
            if (scores[i].grade > 90) {
                scores[i].letterGrade = 'A';
            }
            if (scores[i].grade < 90 && scores[i].grade >= 80) {
                scores[i].letterGrade = 'B';
            }
            if (scores[i].grade < 80 && scores[i].grade >= 70) {
                scores[i].letterGrade = 'C';
            }
            if (scores[i].grade < 70 && scores[i].grade >= 60) {
                scores[i].letterGrade = 'D';
            }
            if (scores[i].grade < 60 && scores[i].grade >= 0) {
                scores[i].letterGrade = 'F';
            }
        }
    }//end enterScores
    

    (change the argumen and replace -> with .)