Reputation: 33
I have this part in my C code.
char** argv_list = parse_cmdline(input);
parse_cmdline() returns also 2D array. I want to free the argv_list. How to find the rows size of argv_list to free it like this :
for(int r = 0 ; r < rows ; r++)
{
free(argv_list[r]);
}
free(argv_list);
Upvotes: 0
Views: 181
Reputation: 148965
In C language, arrays are not first class objects. (This means C does not support arrays in all the ways it supports objects generally. For example, you cannot assign a “value” to an entire array.) When you pass an array to a function, or when a function returns an array, they decay to a pointer to their first element. Said differently, you have no way to know the original size.
Common ways are either to use an auxilliary integer variable (pass a pointer to it) to return the length, or to use a sentinel value to mark the end of the array. This latter convention is used in C strings, that are character arrays where the last used character is a null character. It is also use in argv
(the second parameter of main
) where the last used arg is a null pointer.
Here, as the function returns a pointer to strings (in fact a pointer to pointers), the most common way is to define the last used element of the array to be a NULL pointer, respecting argv
convention.
Upvotes: 2
Reputation: 576
You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.
What you need to do is to keep track of the lenght of the array each time the malloc()
function is called.
Or you can use a different approach as suggested by vmt in comment section you can explicitly append a sentinel value at the end of your array each time you make a call to malloc()
function then later on that array you can loop until to the sentinel to get the array size.
Then you can use
sizeof(array_size)/sizeof(array[0])
this code in order to get the row number and then use it in your code.
Upvotes: 0