Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a struct to null?

Tags:

c

struct

I have a struct that contains two other structs of the same type, and I want to initialize it to have both NULL to start. How do I do that? I've tried the below, but get compiler warnings with gcc.

#include <stdio.h>

typedef struct Segment {
    int microseconds;
} Segment;

typedef struct Pair {
    Segment mark;
    Segment space;
} Pair;

int main()
{
    Pair mark_and_space = { .mark = NULL, .space = NULL };

    return 0;
}

And the compiler warnings:

main.c:14:5: warning: initialization makes integer from pointer without a cast [enabled by default]                                                   
 Pair mark_and_space = { NULL,  NULL };                                                                                                           
 ^                                                                                                                                                
main.c:14:5: warning: (near initialization for 'mark_and_space.mark.microseconds') [enabled by default]                                               

main.c:14:5: warning: initialization makes integer from pointer without a cast [enabled by default]                                                   
main.c:14:5: warning: (near initialization for 'mark_and_space.space.microseconds') [enabled by default] 
like image 915
kibowki Avatar asked Dec 24 '22 14:12

kibowki


1 Answers

In order to intialise two sub-struct, which each contain a single int member to what gets closest to NULL, i.e. init all ints to "0" you can use this code:

#include <stdio.h>

typedef struct Segment {
    int microseconds;
} Segment;

typedef struct Pair {
    Segment mark;
    Segment space;
} Pair;

int main(void)
{
    Pair mark_and_space = { {0}, {0} };

    return 0;
}

If you want to init them to NULL, assuming that you think of pointers, which is the only thing which can cleanly be intialised to NULL, then see the other answers, which basically say "if you want to init to pointer values, then init pointers, not ints".

like image 99
Yunnosch Avatar answered Jan 01 '23 15:01

Yunnosch