简体   繁体   中英

Declaring and allocating memory for a double pointer (char**)

I have a program that requires me to read in large amount of data into a array of strings, and there is a set part of the initial function to declare all variables. The problem is i do not know the actual size of the array of strings until later in the function, so instead of declaring it down below the line that finds the length of the array; I would like to define the variable above then allocate memory after the line. My thinking is:

Ideal:

int declaration;
Char ** DataArray;  //initial declaration at top of file
char * usage;
int Buffer;

//function continues.....

Buffer = SomeNum; //find length of array needed

//allocate ideal size of array(HOW?)

What i am currently doing:

int declaration; //not placing the declaration here, bad programming practice especially
char * usage;    //considering this is an open source project i am working on.
int Buffer;

//function continues.....

Buffer = SomeNum;
char * DataArray[Buffer]; //works, but NOT ideal!

What you are trying to do is called dynamic memory allocation . What you are currently doing using char * DataArray[Buffer] is not part of the C90 standard (it's part of the C99 standard, though; it's also a GCC extension for C90), so you probably shouldn't be using it.

To allocate memory dynamically, use malloc from stdlib.h :

DataArray = malloc(num_elements * sizeof(char *));

malloc() returns a void * to the start of the memory block the system has given to you. Assigning this to a DataArray (which is of type char * ) casts it as a char * .

You can then reference elements from DataArray using either DataArray + index or DataArray[index] , as you would with a regular array.

Unlike statically allocated memory, dynamically allocated memory is not automatically released at the end of the block it was declared in. As such, you have to use free() to release it when you are done with it.

free(DataArray);

If you lose the pointer to the memory block you've been given, though, you can't free() it and you've got yourself what's called a memory leak . There are lots of things that can go wrong with dynamic memory allocation which you have to account for.

For example, the system could simply not have enough memory to give you (or have enough, but not in a continuous block). In that case, malloc() will return NULL , which of course you shouldn't dereference.

Memory management can be quite complicated, so you're probably better off learning it with the help of a book, rather than simply through trial and error. It would certainly be far less frustrating that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM