array of pointers and allocate memory for the strings dynamically

你离开我真会死。 提交于 2019-12-11 04:53:54

问题


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.


回答1:


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);

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

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.




回答2:


try this

gchar *strings[18];
strings[5] = (char*)malloc(sizeof(gchar)*150); //to reserve space in memory
strcpy(strings[5],strAuth);
free (strings[5]); // to delete used buffer 

Regards.



来源:https://stackoverflow.com/questions/17047017/array-of-pointers-and-allocate-memory-for-the-strings-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!