MooCow
MooCow

Reputation: 1426

Initializing a structure in c without the use of memory manipulation methods(malloc... and so on)

I am trying to initialize a struct pointer without using malloc or any memory methods. In doing so, when I try to increase the size of the heap, I get a segmentation fault. Now, I bet I am going about this wrong. I did not initialize all the fields when a assigning dataHeap(I left out an array of structs Node) .Is there a correct way of doing this below or be kindly to point me to a similar problem?

///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   '\0'
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);'
}

Upvotes: 0

Views: 911

Answers (2)

MooCow
MooCow

Reputation: 1426

If I wanted to modify the value by passing it through the method initialize heap, I had to do something slightly different.

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



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

Then when I try to initialize the heap I simply initialize it like so

Heap heap;
initialize_heap(&heap);

Upvotes: 0

reader
reader

Reputation: 516

When you pass a variable to a function, the function receives a copy of that variable. If you pass a value and change it the change isn't reflected outside of the function. To change a value of a pointer you can pass an address of a pointer and then change that pointer through that address.

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);
    ...
}

Upvotes: 1

Related Questions