如何动态分配存储在数组中的单词的内存?
我从屏幕上一一输入单词并将它们发送到一个数组。当然,我可以立即为数组分配大内存,但我想为此动态分配内存。
例如我有一个数组words
。首先,我为其分配一点内存 char *words = malloc(capacity)
,例如,capacity = 15。 ...从屏幕上输入单词...所有分配的内存均已满,我分配更多内存用于进一步工作char *tmp = realloc(words,capacity*2)
。也许,我明白它是如何工作的。但我不知道如何写。也就是如何输入这些单词并将其发送到数组中。你能详细描述一下我应该如何做吗?
示例:
我从屏幕 side left ball rich
输入单词,最后我有一个数组 *arr = ["side", "left", "ball", "rich"]
I input words one by one from the screen and send them to an array. I can, of course, immediately allocate large memory for the array, but I would like to allocate memory for this dynamically.
For example I have an array words
. First, I allocate a little memory for it char *words = malloc(capacity)
, where capacity = 15 for example. ...enter words from the screen... . All allocated memory is full and I allocate more memory for further work char *tmp = realloc(words, capacity*2)
. Probably,I understand how it works. But I can't figure out how to write it. That is, how to enter these words and send them to an array. Could you describe in detail how I should do this?
Example:
I input words from the screen side left ball rich
and at the end I have an array *arr = ["side", "left", "ball", "rich"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在每个索引存储一个单词的情况下有一个指针。
还必须给予注意以释放内存。
片段如下,
demo
You need to have a arry of pointers where each index stores a word.
Also attention has to be given to release the memory.
Snippet as follows,
DEMO