Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing a structure

Tags:

c

gcc 4.4.4 c89

I will be adding to this list. So I am looking to NULL terminate it. However, I am getting a warning: "Initialization makes integer from pointer without a cast"

Why does the it mention integer when I haven't used in that structure?

I was thinking in this case arrays and pointers where the same?

 struct company_prof
    {
        char name[32];
        size_t age;
        char position[32];
    } employee[] = {
        { "Job Bloggs",  23, "software engineer"    },
        { "Lisa Low" ,   34, "Telecomms Technician" },
        { "simon smith", 38, "personal assistist"   },
        { NULL         , -1, NULL                   }
    };

Many thanks for any suggestions,

like image 243
ant2009 Avatar asked Dec 22 '22 02:12

ant2009


1 Answers

You are attempting to initialize a character array with NULL. This does not make any sense. For example, you will get the same warning from

char a[100] = { NULL };

and it makes no sense in exactly the same way.

The "integer" that is mentioned in the diagnostic message is the first element of the character array. char is an integer type in C and when you write

char a[100] = { NULL };

it is an attempt to initialize 0-th element of the array a with NULL. On your platform, NULL is declared as something with pointer type, which is why the diagnostic message is saying that you are attempting to make an integer (a[0]) from a pointer (NULL) without a cast.

An even simpler example might look as follows

char c = NULL;

and it will earn you the same diagnostic message for the very same reasons.

May I ask why you are attempting to initialize a char with NULL? What was your intent?

If you don't intend to write into the name and position arrays after initialization, maybe you should use pointers instead of arrays as in

struct company_prof
    {
        const char *name;
        size_t age;
        const char *position;
    } employee[] = {
        { "Job Bloggs",  23, "software engineer"    },
        { "Lisa Low" ,   34, "Telecomms Technician" },
        { "simon smith", 38, "personal assistist"   },
        { NULL         , -1, NULL                   }
    };

Formally, in this case NULL makes perfect sense. But not in case of array.

But less formally the purpose of that { NULL, -1, NULL } record at the end of the array is not clear to me though. Is is a terminating element of some kind? Why don't you just use the exact size of the array instead of creating a terminating element?

like image 76
AnT Avatar answered Jan 05 '23 02:01

AnT