BaRud
BaRud

Reputation: 3218

array of pointers and allocate memory for the strings dynamically

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.

Upvotes: 1

Views: 762

Answers (2)

nmichaels
nmichaels

Reputation: 50943

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.

Upvotes: 3

Luka Pivk
Luka Pivk

Reputation: 466

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.

Upvotes: -1

Related Questions