指针数组分配内存动态字符串 [英] array of pointers and allocate memory for the strings dynamically

查看:223
本文介绍了指针数组分配内存动态字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题,连接到这个问题
我定义字符的阵列,每个的150b和一个字符串复制到它为:

This question is connected to this question. I am defining an array of characters, each of 150b, and copy a string to it as:

const gchar  *strAuth; 
gchar *strings[18][150];
strcpy(strings[0],strAuth);

这是大多数的情况下,巨大的存储器的浪费,并且可能不足以某些极端的情况下

which is huge memory wastage for most of the cases, and may be insufficient for some extreme cases.

作为参考的问题的建议,这是一个更好的主意使指针数组并分配动态字符串的记忆。

As suggested in question referenced, it is a better idea to "make an array of pointers and allocate memory for the strings dynamically."

我怎样才能做到这一点?
请帮助。

How I can achieve this? Kindly help.

推荐答案

您想使用的malloc 为您的字符串分配空间,并指派它返回到你的 gchar指针*串[X] 为你要分配字符串中每个x。事情是这样的:

You want to use malloc to allocate space for your strings, and assign the pointer it returns to your gchar *strings[x] for each x in strings you want to allocate. Something like this:

gchar *strings[18];
strings[0] = malloc(strlen(strAuth) + 1);
strcpy(strings[0], strAuth);

这是三分球(1号线)和包括空终止(2号线)的字符串的内存动态分配的数组。

That's an array of pointers (line 1) and dynamic allocation of the memory for the string including the null terminator (line 2).

当你在字符串一个特定的字符串完成后,你会想免费(见同一个人页)与免费(串[0]); 。我建议你​​解放出来后,设置已被释放为NULL的指针。

When you're done with a particular string in strings, you'll want to free it (see the same man page) with free(strings[0]);. I recommend you set any pointers that have been freed to NULL after freeing them.

这篇关于指针数组分配内存动态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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