Mental Model
Removing the last item from a list means just ignoring it from now on.
Analogy: Think of a stack of plates where you only take the top plate off to remove it.
Index: 0 1 2 3 4 Array: 10 -> 20 -> 30 -> 40 -> 50 Size: 5
Index: 0 1 2 3 4 Array: 10 -> 20 -> 30 -> 40 -> 50 Size: 5
10 -> 20 -> 30 -> 40 -> 50, size=5
10 -> 20 -> 30 -> 40, size=4
10 -> 20 -> 30 -> 40, size=4
10 -> 20 -> 30 -> 40 -> null
#include <stdio.h> void deleteAtEnd(int arr[], int *size) { if (*size == 0) { printf("Array is empty, nothing to delete.\n"); return; } (*size)--; // reduce size by 1 to delete last element } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d", arr[i]); if (i != size - 1) printf(" -> "); } printf(" -> null\n"); } int main() { int arr[5] = {10, 20, 30, 40, 50}; int size = 5; deleteAtEnd(arr, &size); printArray(arr, size); return 0; }
if (*size == 0) {(*size)--;for (int i = 0; i < size; i++) {if (*size == 0) {
(*size)--;
arr of size n in C?n by 1 removes last element logically.free is for dynamic memory. arr = arr - 1; is invalid pointer arithmetic.int arr[5] = {10, 20, 30, 40, 50};
int n = 5;
n = n - 1;
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}n is 5. After n = n - 1;, n becomes 4, so loop runs from 0 to 3.arr of size n.void deleteEnd(int arr[], int n) {
arr[n] = 0;
n = n - 1;
}n by 1. Setting arr[n] to 0 is invalid and does not delete element.int *arr and current size n, which of the following correctly deletes the last element and updates the array size safely in C?n by 1 and resize memory using realloc to avoid wasted space.Pass the test and this pattern moves unknown