I am currently trying to allocate the same amount of memory for a double pointer. I take in a char** and want to use a bubble sort on that char** . So I create a temp char** and now I’m wondering how to correctly allocate enough memory so that I can return that temp char** to another method.
I know the way I’m allocating right now doesn’t look right and it certainly doesn’t work…otherwise I wouldn’t be asking this question. If someone could respond with some helpful advice, I would greatly appreciate it!
char** bubble_sort(char **filenames, int n)
{
int i;
char **new_list;
new_list = malloc(sizeof(filenames));
for (i = 0; i < n; i++)
{
// malloc(file_list.size * sizeof(int));
new_list[i] = filenames[i];
}
for (i = 0; i < n; i++)
{
printf("%d: %s\n", i, new_list[i]);
}
int x;
int y;
for(x=0; x<n; x++)
{
for(y=0; y<n-1; y++)
{
if(new_list[y]>new_list[y+1])
{
char *temp = new_list[y+1];
new_list[y+1] = new_list[y];
new_list[y] = temp;
}
}
}
for (i = 0; i < n; i++)
{
printf("%d: %s\n", i, new_list[i]);
}
return new_list;
}
Here is the working copy of the program:
Still, keep in mind that your programming style resembles more to C than C++ (which is not always a bad thing).
If you want to allocate new strings for your array elements, you should change the first for like this:
And this is the C version (first one was the C++ version). Note that the string array has all its elements newly allocated, and is not using the initial strings from the input parameter.: