重新分配数组(C99) [英] Reallocating an array (C99)

查看:78
本文介绍了重新分配数组(C99)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准指定未分配空间的内容未定义如果新尺寸更大.

The standard specifies that the contents of reallocated space is undefined if the new size if larger.

如果保留以前分配的空间的内容很重要,那么重新分配数据的最佳方法如下:将其复制到堆栈中,将其从堆中释放出来,在堆上分配更多空间,然后复制回堆吗还有另一种安全的方法吗?

If preserving the contents of the previously-allocated space is important, is the best way to reallocate data as follows: copying it to the stack, freeing it from the heap, allocating on the heap with more space, and copying back to the heap? Is there another safe way to do this?

实现像动态增长的数组那样仅以链表形式增长的数据结构的最佳方法是吗?

Would the best way to implement a data structure like a dynamically growing array that only grows be in the form a linked list?

推荐答案

未指定对象的新分配部分"的内容.您的内容仍将位于返回的内存区域的开头.

The contents of the "newly allocated portion of the object are unspecified." Your content will still be at the beginning of the returned memory region.

说我做

char *p = malloc(6);
if(p == NULL) { ... }
memcpy(p, "Hello", 6);
char *temp = realloc(p, 12);
if(temp == NULL) { ... }
p = temp;

p的前6个字符保证为'H','e','l','l','o','\ 0',无论新的p是否相同与旧的p一样.其余6个新"字符是未定义的.

The first 6 characters at p are guaranteed to be 'H', 'e', 'l', 'l', 'o', '\0', regardless of whether new p is the same as old p. The remaining 6 "new" chars are all that's undefined.

这篇关于重新分配数组(C99)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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