Fixed the error of the C/C array insertion element loop condition #1797
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🐛 Bug Fix: Array Insert Function Data Loss
Problem Description
The current
insert
function in the array implementation has a logical error that causes data loss during insertion operations.Root Cause Analysis
The issue is in the loop initialization:
Problem: Starting from
i = size - 1
doesn't create space for the new element and overwrites the element at the insertion index.Example Demonstrating the Bug
Scenario: Insert
5
at index1
in array[1, 2, 3, 4]
Current behavior (incorrect):
❌ Result: Element
2
at original index 1 is lost!Expected behavior (correct):
✅ Result: All original elements preserved, new element inserted correctly.
Solution
Change the loop initialization from
i = size - 1
toi = size
:Files Changed
codes/c/chapter_array_and_linkedlist/array.c
(or wherever the insert function is located)Testing
Impact
Related Issues
This bug would cause incorrect results in any code following this tutorial implementation, potentially misleading learners about proper array insertion algorithms.