This is the code with extra m no of memory reallocation:
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,m,*ptr;
printf("Enter the number of varriables you want to add in array : ");
scanf("%d",&n);
ptr = (int *) malloc(n*sizeof(int));
for(int i=0;i<n;i++)
{
printf("\nEnter the value of element %d : ", i+1);
scanf("%d",&ptr[i]);
}
printf("\nYour array is : ");
for (int i = 0; i < n; i++)
{
printf("%d ",ptr[i]);
}
printf("\nEnter the number of varriables you want to add in array : ");
scanf("%d",&m);
**ptr = (int *) realloc(ptr,sizeof(int)*m);**
for(int i=0;i<m;i++)
{
printf("\nEnter the value of element %d : ", i+1);
scanf("%d",&ptr[n+i]);
}
printf("\nYour array is : ");
for (int i = 0; i < (n+m); i++)
{
printf("%d ",ptr[i]);
}
free(ptr);
return 0;
}
and the next code is without particular no of memory allocation:
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,m,*ptr;
printf("Enter the number of varriables you want to add in array : ");
scanf("%d",&n);
ptr = (int *) malloc(n*sizeof(int));
for(int i=0;i<n;i++)
{
printf("\nEnter the value of element %d : ", i+1);
scanf("%d",&ptr[i]);
}
printf("\nYour array is : ");
for (int i = 0; i < n; i++)
{
printf("%d ",ptr[i]);
}
printf("\nEnter the number of varriables you want to add in array : ");
scanf("%d",&m);
**ptr = (int *) realloc(ptr,sizeof(int));**
for(int i=0;i<m;i++)
{
printf("\nEnter the value of element %d : ", i+1);
scanf("%d",&ptr[n+i]);
}
printf("\nYour array is : ");
for (int i = 0; i < (n+m); i++)
{
printf("%d ",ptr[i]);
}
free(ptr);
return 0;
}
These two code is giving me same output in vs code, with out any runtime error nor any problem. so my question is,
why should I specify ptr = (int *) realloc(ptr,sizeof(int)*m);
in spite of ptr = (int *) realloc(ptr,sizeof(int));
?
and how much memory exactly the second one allocating?
You want
ptr = (int *) realloc(ptr,sizeof(int)*(n+m));
since you want enough space for n+m
int
values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.