dhokar.w
dhokar.w

Reputation: 470

Initializing an array with NULL pointer with GCC throw error

I am using GCC and IAR to compile some C code.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

uint8_t tab[] = NULL;

this exmple code throw this error with GCC : error: invalid initializer

With IAR compiler the syntax is accepted

What is wrong here with GCC and why it is accepted by IAR compiler?

Upvotes: 0

Views: 489

Answers (2)

Hitokiri
Hitokiri

Reputation: 3699

You can initialize the array with any positive number of element, but you can not assign the array with NULL or int. But you can compare the array with NULL pointer.

For example:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

uint8_t tab[] = {}; // it's OK but it does not make sense with 0 element in the array
// uint8_t tab[] = {0}; it's OK size of array  = 1
// uint8_t tab[] = {0,1,2,3}; // it is OK, size of array = 2
int main() {

    if(tab == NULL) { // it's OK, you can compare
        // do sth
    }
    // tab = NULL it's not accepted
    // tab = 0x1010101 it's not accepted also

    printf("%lu\n", sizeof(tab)); // it will print 0
    return 0;
}

You can also use dynamically array with size = 0:

uint8_t *tab2;
...
tab2 = malloc(0);
// do something
tab2 = realloc(tab2, 3); // re-allocate the pointer for lager size

Upvotes: 0

Arish Khan
Arish Khan

Reputation: 750

If you look inside the header files than you can notice that NULL is actually

#define NULL ((void*)0) // a void pointer type data.

whereas, when you declare an array with following syntax

uint8_t tab[] // This is not basically a pointer | it is an array.

you are assigning a pointer data type to an array datatype that is the issue.

Upvotes: 1

Related Questions