islam zidan islam zidan - 3 months ago 19
C Question

Can't understand trees in C

I'm starting to work with trees in C and I made this really simple program, but somehow it crashes. I don't know why but if you could take a look at my code and tell me that would be great.

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>

typedef struct node
{
bool is_word;
struct node* children[27];
}
node;

node* root;

int main()
{
root->children[0]=NULL;
}

Answer

Before using a pointer you have to initialize it. In this particular example, you will most likely get a NULL pointer since according to the C standard global variables should be initialized to 0.

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>

typedef struct node
{
    bool is_word;
    struct node* children[27];
}
node;

node* root;

int main()
{
    root = malloc(sizeof(node));
    root->children[0]=NULL;
    free(root);
}
Comments