所以我有列表被添加到堆中;例如:
n = [[1, 5, 93],
[2, 6, 44],
[4, 7, 45],
[6, 3, 12]]
heapq.heapify(n)
print(n)
Run Code Online (Sandbox Code Playgroud)
这将根据列表的第一个元素进行比较和排序。
我的问题是,如何对 heapq 进行排序,以便比较每个列表的第三个元素?例如,上面的列表将按以下顺序从 heapq 访问:
[[6, 3, 12],
[2, 6, 44],
[4, 7, 45],
[1, 5, 93]]
Run Code Online (Sandbox Code Playgroud) 当使用memcpy()时,它是否释放了原始内存?这是一个评估,所以我不能分享orignal代码.代码有效,但valgrind显示了声明原始数组的内存泄漏.
例如:
//first array
animal** dogs= malloc(sizeof(animal*) * 5);
for(int i = 0; i < 5; i++){
dogs[i] = malloc(sizeof(animal));
dogs[i]->name = "doggo";
}
//second array
animal** cats; = malloc(sizeof(animal*) * 3);
for(int i = 0; i < 3; i++){
cats[i] = malloc(sizeof(animal));
cats[i]->name = "Kitty";
}
//third array -- combination of first and second array
animal** all_animals = malloc(sizeof(animal*) * 8);
memcpy(all_animals, dogs, sizeof(animal*) * 5);
memcpy(all_animals + 5, cats, sizeof(animal*) * 3);
Run Code Online (Sandbox Code Playgroud)
我需要释放狗,猫和all_animals吗?或者仅释放all_animals就足够了?
1| typedef struct container{
2| char* abc;
3| }container;
4|
5|
6| int main(void){
7|
8| container* xyz = malloc(sizeof(container));
9|
10| xyz->abc = malloc(10);
11| xyz->abc = "abcdefghi\0";
12|
13| free(xyz->abc);
14| free(xyz);
15| }
Run Code Online (Sandbox Code Playgroud)
根据Valgrind的说法,第10行有泄漏,这意味着免费(xyz-> abc)不起作用.我怎么能解脱这个?