I have a question regarding dynamic allocation.
Why do the array values change after using realloc? It works fine if the initial size of the array is greater than the next size (e.g. 10 20)
but if the initial size of the array is lesser than the next size (e.g. 20 10)
, the code gives me garbage values.
The code works properly in local side but when I try it on online compilers, it does not work the way it's supposed to.
Is there anything wrong with my code? Or is it a problem with online compilers? And am I using the realloc
function properly?
#include<stdio.h>
#include<stdlib.h>
void print(int *ptr, int size);
void reallocate(int *ptr, int size);
void assign(int *ptr, int size);
int main(void) {
int n;
// Set initial size for array
scanf("%d",&n);
int *arr = (int*) malloc(n * sizeof(int));
// Assign values from 0 to n-1
assign(arr, n);
// Print values assigned
print(arr, n);
printf("\n");
// Set new size for reallocation
scanf("%d",&n);
reallocate(arr, n);
// Assign values again
assign(arr, n);
// Print values
print(arr,n);
return 0;
}
// Prints values of the array
void print(int *ptr, int size) {
for(int i = 0; i < size; i++) printf("%d ",ptr[i]);
}
// Reallocates new size for array
void reallocate(int *ptr, int size) {
ptr = realloc(ptr, size*sizeof(int));
}
// Assigns values from 0 to n-1
void assign(int *ptr, int size) {
for(int i = 0; i < size; i++) ptr[i] = i;
}
I hope for your responses.