小编Adi*_*rel的帖子

Python heapq:如何使用列表列表的第 n 个元素对堆进行排序?

所以我有列表被添加到堆中;例如:

 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)

python

4
推荐指数
1
解决办法
4003
查看次数

memcpy释放原始内存吗?

当使用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就足够了?

c

0
推荐指数
1
解决办法
3421
查看次数

如何在结构中释放char*?

 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)不起作用.我怎么能解脱这个?

c free pointers

-2
推荐指数
1
解决办法
301
查看次数

标签 统计

c ×2

free ×1

pointers ×1

python ×1