In my code, I am allocating memory for 2 elements first, then assigning value at each memory location. when I print them I get their values.
then I allocate memoary for more 3 elements then assigning value at each memory location. when I print them I get their values.
Now I have total five elements which are stoared at five memory location.
I want to print all the five elements but when i print their value I don't get expected value
Memory successfully allocated using malloc.Code:#include <stdio.h> #include <stdlib.h> int main() { int i; // Dynamically allocate memory using malloc() int* ptr = (int*)malloc(2 * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr != NULL) { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.\n"); // Get the elements of the array for (i = 0; i < 2; i++) { printf("The elements of the array are: "); scanf ("%d", ptr + i); } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < 2; i++) { printf("%d, ", *(ptr + i)); } } // Dynamically allocate memory using malloc() ptr = (int*)realloc(ptr, 3 * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr != NULL) { printf("\n Enter the 3 more the elements of the array are \n"); // Get the elements of the array for (i = 0; i < 3; i++) { printf("The elements of the array are: "); scanf ("%d", ptr + i); } // Print the elements of the array printf("\nThe elements of the array are: "); for (i = 0; i < 3; i++) { printf("%d, ", *(ptr + i)); } } // Print the elements of the array printf("\nThe elements of the array are: "); for (i = 0; i < 5; i++) { printf("%d, ", *(ptr + i)); } return 0; }
The elements of the array are: 1
The elements of the array are: 2
The elements of the array are: 1, 2,
Enter the 3 more the elements of the array are
The elements of the array are: 3
The elements of the array are: 4
The elements of the array are: 5
The elements of the array are: 3, 4, 5,
The elements of the array are: 3, 4, 5, 0, 0,
Why I don't get output 1, 2, 3, 4, 5?
Edit : int* ptr = (int*)malloc(5 * sizeof(int));