C语言数组操作函数问题求助:数组最大长度限制逻辑失效排查
Hey there! Let's walk through the problems in your code and fix them step by step. I see a few key issues that are preventing your max length restriction from working, plus some other potential bugs that could cause unexpected behavior:
Key Problems Identified:
Invalid array declaration:
int marks[] = {};isn't valid C syntax. You can't declare an empty fixed-size array like this—this will lead to undefined behavior when you try to write values to it.Size check happens too late: You're checking if
size >=200after you've already calledinit_arrayand tried to fill the array. By then, if the size was over 200, you've already attempted to write beyond the array's bounds (a dangerous buffer overflow).Missing argument in printf: The line
printf("Please enter %d values: \n");is missing thesizeargument for the%dplaceholder. This is undefined behavior and will likely print garbage instead of the correct number of values.No check for positive size: If the user enters a negative number for size, your loops will run incorrectly (since
i < sizewill be true for negative values, leading to more undefined behavior).
Corrected Code:
Here's a fixed version that addresses all these issues, using dynamic memory allocation to handle variable array sizes safely:
#include <stdio.h> #include <stdlib.h> // Required for malloc and free void init_array(int ar[], int size) { int i; // Fixed printf to include the size argument printf("Please enter %d values: \n", size); for (i = 0; i < size; i++) { scanf("%d", &ar[i]); } printf("Elements in array are:"); for (i = 0; i < size; i++) { printf("%d, ", ar[i]); } // Clean up the trailing comma for cleaner output printf("\b\b \n"); } int main() { int size; printf("The size of list: "); scanf("%d", &size); // Validate size immediately after input if (size <= 0 || size > 200) { printf("Invalid size! Please enter a number between 1 and 200.\n"); return 1; // Exit with error code } // Dynamically allocate memory for the array int *marks = malloc(size * sizeof(int)); if (marks == NULL) { printf("Memory allocation failed!\n"); return 1; } init_array(marks, size); // Release allocated memory to avoid leaks free(marks); return 0; }
Explanation of Changes:
Valid array handling: We use
mallocto dynamically allocate an array of the requested size (only after validating the size). This ensures we only use as much memory as needed, and avoids the invalid empty array declaration.Early size validation: We check if the size is between 1 and 200 right after reading it. If it's invalid, we print an error and exit immediately, preventing any unsafe operations.
Fixed printf: Added the
sizeargument to the printf call so it correctly displays the number of values needed.Memory management: We use
freeto release the dynamically allocated memory, which is critical to avoid memory leaks in longer programs.Cleaned up output: Added a small fix to remove the trailing comma in the array printout (using
\b\bto backspace over the last comma and space).
If you prefer to use a fixed-size array instead of dynamic allocation, you could declare int marks[200]; and then only use it if the size is <=200—but dynamic allocation is more efficient since it doesn't allocate the full 200 integers unless needed.
Content of the question originates from Stack Exchange, question author Amanda_Sterling

