在C语言中,是否可能只释放数组的第一个或最后一个位置? [英] In C, is it possible do free only an array first or last position?

查看:111
本文介绍了在C语言中,是否可能只释放数组的第一个或最后一个位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,但是不需要它的第一个(或最后一个)位置.因此,我将新变量指向数组的其余部分,但应释放数组的第一个/最后一个位置.例如:

I've an array, but I don't need its first (or last) position. So I point a new variable to the rest of the array, but I should free the array first/last position. For instance:

p = read_csv_file();
q = p + 1; // I don't need the first CSV file field
// Here I'd like to free only the first position of p
return q;

否则,我必须将数组存储到其他变量(不包括第一个位置)中,然后释放原始数组.像这样:

Otherwise I've to memcpy the array to other variable, excluding the first position, and then free the original array. Like this:

p = read_csv_file();
q = (int*) malloc(sizeof(int) * (SOME_SIZE - 1));
memcpy(q, p+1, sizeof(int) * (SOME_SIZE - 1));
free(p);
return q;

但是接下来,我将承担复制所有阵列的开销.

But then I'll have the overhead of copying all the array.

有可能只释放数组的单个位置吗?

Is this possible to only free a single position of an array?

推荐答案

否.您只能 free()完整的块,该块是通过调用 malloc()(或 malloc()的朋友之一)获得的,不是那个块的一部分.

No. You can only free() a complete block obtained from a call to malloc() (or one of malloc()'s friends), not a piece of that block.

您最好的选择可能是将分配的块保持原样,而仅使用指向索引1的元素的指针,就好像它是数组的开始(而忽略最后一个元素).

Your best bet is probably to leave the allocated block as-is and just use a pointer to the element at index one as if it were the beginning of the array (and ignore the last element).

使用 memcpy 是可行的.

您还可以将所有元素向左移动一(即,将索引1处的元素移到索引0等),然后调用 realloc()来调整块的大小,并删除最后两个元素.不过,这并不是一个好主意,因为最可能的结果是(a)底层堆分配实际上不会调整大小,您会四处移动而没有任何收益,或者(b)基础堆分配将被调整大小,并且所有内容将再次移动.

You could also shift all of the elements to the left by one (i.e., move the element at index one to index zero and so forth) and then call realloc() to resize the block and remove the last two elements. This isn't really a good idea, though, because the most likely outcome is that either (a) the underlying heap allocation won't actually be resized and you'll have moved thing around and gotten no benefit, or (b) the underlying heap allocation will be resized and everything will get moved a second time.

这篇关于在C语言中,是否可能只释放数组的第一个或最后一个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆