Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd use of { } in legacy C program and incompatible pointer conversion

Tags:

c

I have some legacy C code that contains the following line:

char line[max_line] = {NULL}

where in stddef.h, NULL is defined as:

#define NULL ((void*)0)

When trying to compile the code with icx, I am getting a error about incompatible pointer to integer conversion initializing 'char' with an expression of type 'void *'

Two questions:

  1. I've only seen curly braces used in C to delineate a block of code. What is the meaning of {NULL}?
  2. How should I modify the code to eliminate the incompatible pointer conversion error?

I tried:

char line[max_chars] = "";

and that compiled OK, but I'm still confused by the meaning of {NULL}

like image 906
Tom Gederberg Avatar asked Oct 22 '25 05:10

Tom Gederberg


1 Answers

Conjecture: This code was written by somebody who confused the NULL macro with the null character. The NULL macro is intended for use as a null pointer constant and should not be used to represent a character or integer value.

The code could have worked without complaint in some C implementations because the C standard permits NULL to be defined as 0 (or other integer constant expression with the value zero). So the code would be char line[max_line] = {0}, which initializes the array to a zero first element (explicitly) and zero in the remaining elements (by default). (There should also be a semicolon at the end, or other continuation of the declaration.)

In your C implementation, NULL is defined as ((void*)0), which is also allowed by the C standard. This form is generally preferable, as making NULL a pointer type allows the compiler to detect some errors, as has occurred here. (Allowing the other form, an integer constant, was likely a deference to existing C implementations.)

  1. I've only seen curly braces used in C to delineate a block of code. What is the meaning of {NULL}?

This is normal syntax for listing the initial values for an array or structure, as in int array[3] = { 1, 2, 3 };. (Braces may also be used, optionally, for initializing a scalar, as in int x = { 4 };.)

  1. How should I modify the code to eliminate the incompatible pointer conversion error?

Change NULL to 0 or, to emphasize it is a character, '\0': char line[max_line] = { '\0' };. Using "" as you did is also okay.

like image 51
Eric Postpischil Avatar answered Oct 23 '25 20:10

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!