C语言成绩册堆内存改造作业问题求助及C语言学习指导需求
Fixing Your C Grade Book Code with Heap Memory
Let's walk through fixing your code step by step—there are a few key issues with memory allocation, variable usage, and input handling that we can sort out together to meet your assignment requirements.
First, Let's Break Down the Problems in Your Original Code
- Heap Memory Misuse: You declared
gradeNumsbut never used it to store grades (you were relying on stack-based arrays instead). Also, yourmalloccall had a critical error:gradeBook * sizeof(int)doesn't make logical sense (you can't multiply an array by a memory size value). - Uninitialized Variables:
totalEnteredwasn't set to 0 initially, and you usedi(which stayed at 0 the whole time) to control your print loop—so no grades ever got printed. - Input Handling Gaps: You didn't validate if grades fell between 0-100, and your
strncmpcheck only handled uppercase 'D' (users might type lowercase 'd'). Plus,fgetscaptures the newline character from input, which can break string comparisons. - Print Loop Logic: You tried to print values from
gradeBookbut stored grades inintArray, and your loop condition was completely disconnected from the actual number of grades entered.
Corrected Code with Explanations
Here's a revised version that meets all your assignment requirements:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // Define the maximum number of grades we can store (adjustable if needed) const int MAX_GRADES = 15; int* grades = NULL; int totalEntered = 0; char input[15]; // Allocate heap memory for storing grades grades = (int*)malloc(MAX_GRADES * sizeof(int)); if (grades == NULL) { printf("Memory allocation failed! Program exiting.\n"); return 1; } printf("=== Grade Entry ===\n"); printf("You can enter up to %d grades (0-100). Type 'D' or 'd' when finished.\n\n", MAX_GRADES); while (totalEntered < MAX_GRADES) { printf("Enter grade #%d: ", totalEntered + 1); fgets(input, sizeof(input), stdin); // Remove the newline character that fgets automatically captures input[strcspn(input, "\n")] = '\0'; // Check if user wants to stop entering grades if (strcmp(input, "D") == 0 || strcmp(input, "d") == 0) { break; } // Convert input to integer and validate the grade range int grade = atoi(input); if (grade >= 0 && grade <= 100) { grades[totalEntered] = grade; totalEntered++; } else { printf("❌ Invalid grade! Please enter a number between 0 and 100.\n"); } } // Print the entered grades printf("\n=== Entered Grades ===\n"); printf("You entered %d grades:\n", totalEntered); for (int j = 0; j < totalEntered; j++) { printf("%d ", grades[j]); } printf("\n"); // Free the allocated heap memory (critical to avoid memory leaks) free(grades); grades = NULL; // Set pointer to NULL to avoid dangling pointer issues return 0; }
Key Changes Made
- Proper Heap Memory Usage: We allocate memory with
mallocspecifically for storing grades, and we add a check to ensure the allocation succeeded (a standard practice to prevent crashes from out-of-memory errors). - Validated Input: We ensure grades are within the 0-100 range, handle both uppercase and lowercase 'D' for exiting, and clean up the newline character from
fgetsto avoid unexpected behavior. - Correct Print Logic: The print loop uses
totalEntered(the actual count of grades input) to iterate, so every entered grade gets printed. - Memory Cleanup: We free the heap memory at the end of the program, and set the pointer to
NULLto avoid dangling pointer bugs.
Extra Tips for Improvement
- If you want to handle non-numeric input more gracefully (like users typing random letters instead of D/d), use
strtolinstead ofatoi—it lets you verify if the conversion to an integer actually succeeded. - If you need to support more grades than the initial maximum, you can use
reallocto dynamically expand the heap memory as the user enters more grades.
内容的提问来源于stack exchange,提问作者Martie W.
相关产品推荐
相关产品推荐

