Smerald Guci
Smerald Guci

Reputation: 25

How to realloc shrinking the size of an array?

Example: my array contains integers {1,2,3,4} I want to resize my array in order to contain {2,3,4} and when I do array[0] it should give me 2.

Upvotes: 1

Views: 3276

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753785

When you shrink an array with realloc(), you can remove space at the end of the array, but not at the beginning of the array. Therefore, to achieve the result you want, you'd have to copy the portion of the array you want to keep to its new position and then resize the array:

/* setup */
int *data = malloc(4 * sizeof(int));  // Error check omitted
for (int i = 0; i < 4; i++)
    data[i] = i + 1;
/* setup complete */

/* Move elements before shrinking array */
memmove(&data[0], &data[1], 3 * sizeof(int));  // Safe move
int *new_data = realloc(data, 3 * sizeof(int));
if (new_data != 0)
    data = new_data;

I'm not sure whether a 'shrinking' realloc() does ever return NULL (but the standard doesn't say it can't), so the code takes no chances. Many people would write data = realloc(data, 3 * sizeof(int)); and run the risk, and they'd get away with it almost all the time. Note that a 'growing' realloc() really can return NULL and you can then leak memory if you use the old_ptr = realloc(old_ptr, new_size) idiom.

Usually, a 'shrinking' realloc() will return the original pointer (unless you shrink it to zero size, when it may return NULL). A 'growing' realloc() can often change where the data is stored.

Upvotes: 3

Related Questions