Header file:
stdlib.h
Synopsis:
void *realloc(void *ptr, size_t sz);
Description:
It changes the size of the block pointed by ptr to size sz and returns the pointer to that modified block. Data in old block remains unchanged. Returns NULL on error.
realloc function C example:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
int *data, i;
/* dynamic memory allocation for 5 integers */
data = (int *)malloc(sizeof(int) * 5);
/* initilization */
for (i = 0; i < 5; i++) {
data[i] = i;
}
/* reallocation */
data = (int *)realloc(data, sizeof(int) * 10);
/*
* data in old block remains undisturbed.
* Writing data in newly allocated block alone
*/
for (i = 5; i < 10; i++) {
data[i] = i;
}
/* printing the result */
for (i = 0; i < 10; i++) {
printf("data[%d]: %d\n", i, data[i]);
}
/* freeing dynamically allocated block */
free(data);
return 0;
}
#include<stdlib.h>
#include<string.h>
int main() {
int *data, i;
/* dynamic memory allocation for 5 integers */
data = (int *)malloc(sizeof(int) * 5);
/* initilization */
for (i = 0; i < 5; i++) {
data[i] = i;
}
/* reallocation */
data = (int *)realloc(data, sizeof(int) * 10);
/*
* data in old block remains undisturbed.
* Writing data in newly allocated block alone
*/
for (i = 5; i < 10; i++) {
data[i] = i;
}
/* printing the result */
for (i = 0; i < 10; i++) {
printf("data[%d]: %d\n", i, data[i]);
}
/* freeing dynamically allocated block */
free(data);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
data[0]: 0
data[1]: 1
data[2]: 2
data[3]: 3
data[4]: 4
data[5]: 5
data[6]: 6
data[7]: 7
data[8]: 8
data[9]: 9
data[0]: 0
data[1]: 1
data[2]: 2
data[3]: 3
data[4]: 4
data[5]: 5
data[6]: 6
data[7]: 7
data[8]: 8
data[9]: 9
No comments:
Post a Comment