在c中初始化一个结构,而不使用内存操作方法(malloc..等等)



我正在尝试在不使用malloc或任何内存方法的情况下初始化结构指针。在这样做的过程中,当我试图增加堆的大小时,会出现分段错误。现在,我打赌我做错了。在分配dataHeap时,我没有初始化所有字段(我遗漏了一个structs Node数组)。下面有正确的方法吗?或者请指出类似的问题?

///node_heap.h///
8 #ifndef NODE_HEAP_H
9 #define NODE_HEAP_H
10 
11 #include <stdio.h>
12 #include <stdlib.h>
13 
15 #define NUL   ''
16 
18 #define NUM_BITS   8
19 
21 #define MAX_CODE   NUM_BITS + 1
22 
24 #define NSYMS      1 << NUM_BITS
25 
37 typedef struct Symbol_S {
39     size_t frequency;
40 
42     size_t bit;
43 
45     char symbol;
46 
48     char codeword[MAX_CODE];
49 } Symbol;
50 
60 typedef struct Node_S {
62     size_t frequency;
63 
65     size_t num_valid;
66 
68     Symbol syms[NSYMS];
69 
70 } Node;
71 
82 typedef struct Heap_S {
84     size_t capacity;
85 
87     size_t size;
88 
90     Node array[NSYMS];
91 } Heap;
 /////////
//Heap.c//
#include "node_heap.h"
Heap dataHeap;
void initialize_heap( Heap * heap){
dataHeap = (Heap){0,250}; //size_T size, size_T max_HeapSize, Node[255]
heap = &dataHeap;
}
increaseSize(*Heap heap){
heap->size++;
}
/////////// 
// Main.c//
///////////
#include "node_heap.h"
main(){
Heap* myHeap = NULL;
initialize_heap(myHeap);
increaseSize(myHeap);'
}

当您将变量传递给函数时,函数将接收该变量的副本。如果传递一个值并对其进行更改,则更改不会反映在函数之外。要更改指针的值,可以传递指针的地址,然后通过该地址更改指针。

void initialize_heap( Heap** heap)
{
    dataHeap = (Heap){0,250}; //size_T size, size_T max_HeapSize, Node[255]
    *heap = &dataHeap;
}
main()
{
    Heap* myHeap = NULL;
    initialize_heap(&myHeap);
    ...
}

如果我想通过方法initialize heap来修改值,我必须做一些稍微不同的事情。

   Heap dataHeap;
   void initialize_heap( Heap *heap){
   heap->size = 0;
   heap->max_size = 255;

   }
   increaseSize(*Heap heap){
   heap->size++;
  }`

然后,当我尝试初始化堆时,我只需像这样初始化

Heap heap;
initialize_heap(&heap);

最新更新