在 C 中的字符串数组中重新分配内存

发布于 2024-10-31 06:34:27 字数 563 浏览 5 评论 0原文

我试图满足 valgrind 的要求并提出一个很好的实现,但我遇到了一个障碍。本质上我想做的就是将数组中的两个字符串减少为一个。假设 arr 包含

{ "One", "Two", "Three" }

并且每个字符串的内存分配已经完成(a la arr[1] = malloc(strlen("one") + 1) 和 strcpy(arr[1], "One")

进行一些字符串操作并尝试执行以下操作:

strcpy(arr[1],"OneTwo");

并删除 arr[2] 但这本质上是有问题的,因为 arr[1] 的内存分配已经改变。有件事告诉我,再次执行 malloc 会很糟糕。

我可以进行realloc,但这需要释放arr[2]并将其后的所有内容向下移动一个空间并重新分配。我也可以这样做 arr[2] = NULL 但 valgrind 不同意。

任何提示将不胜感激。

I'm trying to satisfy valgrind and come up with a nice implementation, but I'm coming across a snag. Essentially what I'm trying to do is reduce two strings in an array to one. Let's say arr contains

{ "One", "Two", "Three" }

And that the memory allocation for each string has been done as it should be (a la arr[1] = malloc(strlen("one") + 1) and strcpy(arr[1], "One").

I do some string manipulation and try to do:

strcpy(arr[1],"OneTwo");

and remove arr[2] but this is inherently problematic because the memory allocation for arr[1] has changed. Something tells me that doing malloc again would be bad.

I could do realloc but that would require either freeing arr[2] and shifting everything after it down one space and realloc'ing. I could also do arr[2] = NULL but valgrind disagrees.

Any hints would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜尕妞 2024-11-07 06:34:27

重新分配arr[1]并将arr[2]附加到字符串末尾,然后释放arr[2](并设置arr[ 2] = NULL 以避免稍后混淆)。

reallocate arr[1] and append arr[2] to the end of the string, then free arr[2] (and set arr[2] = NULL to avoid confusion later).

小兔几 2024-11-07 06:34:27

为什么reallocing arr[1]需要对其他内容进行任何修改?

strcpy( arr[1] = realloc( arr[1], sizeof "OneTwo" ), "OneTwo" );
free( arr[2] );
arr[2] = NULL;

我觉得不错。这里的 arr[2] 之后没有任何内容,因此无需进行任何转换。如果有,那么是的,从任何数组的中间删除都要求您向下移动以下元素。

Why would reallocing arr[1] require any modification of anything else?

strcpy( arr[1] = realloc( arr[1], sizeof "OneTwo" ), "OneTwo" );
free( arr[2] );
arr[2] = NULL;

Looks good to me. There's nothing after arr[2] here so no shifting to do. If there were, then yes, removing from the middle of any array demands that you shift down the following elements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文