C动态字符串长度 [英] C dynamic string length

查看:162
本文介绍了C动态字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中创建动态字符串有不同的方法(长度不断变化)。经过一些google搜索,主要的方法是使用 realloc()

There are different ways of creating dynamic strings in C (with length that constantly changes). After some google search, the main way of doing this is to use realloc().

我实现这一点的方法是使用每个节点的32字节块的链表。

A way I implemented this is using linked lists with 32 bytes chunks for each node.

我在想如果有更好的方法来解决这个问题,除了使用realloc()和链接列表,以及每个方法的缺点和优点。

I was wondering if there are better ways of tackling this apart from using realloc() and linked lists, and what the cons and pros for each method are.

编辑我这样做的原因是因为我正在从一个套接字recv()接收动态数据,并且正在寻找一种灵活的存储方式,而不需要分配大量的数据,

EDIT The reason I am doing this is because I'm receiving dynamic data from a socket recv(), and was looking for a flexible way of storing it, without allocating huge amounts of data that aren't needed.

推荐答案

您可以重定位到不同的预定义大小。例如,当缓冲区已满时,它的大小是其大小。

You can realloc to different predefined sizes. For example, when the buffer is full, double its size.

使用链表是一个好主意,但数据不是连续的(您不能通过整个结构到 printf ),索引需要更多的计算(O(N))。一个主要的优点是附加字符串(在任一端)是O(1)。

Using a linked list is a good idea, but the data is not continuous (you can't pass the whole structure to printf, for example) and indexing takes more calculations (O(N)). A major advantage is that appending strings (at either end) is O(1).

这篇关于C动态字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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