1

I have the following code, I want to initialize the char array to NULL.

getting the following error

error: expected an expression g_device->name1[NAME_LENGTH-1] = {'\0'};

typedef struct device_ {

    uint32_t id;
    char name1[NAME_LENGTH];
    char name2[NAME_LENGTH];

} device_t;

device_t  *g_device = NULL;


void init_device(void)
{

    g_device = malloc(sizeof(device_t));
    g_device->id = 0;
    g_device->name1[NAME_LENGTH-1] = {'\0'};
    g_device->name2[NAME_LENGTH-1] = {'\0'};
}
1
  • {'\0'} is not a valid expression in C. You probably want g_device->name1[0] = '\0'; (note, place '\0' in the beginning). Commented Jun 29, 2016 at 7:12

2 Answers 2

3

You cannot assign arrays in C, plus the types don't match anyway, g_device->name1[NAME_LENGTH-1] is a char and {'\0'} is a char[1].

Use strcpy:

strcpy( g_device->name1 , "" );

or manually terminate the array:

g_device->name1[0] = '\0';

Notice that you should set the first character to 0, not the last.

The above two examples will of course leave other elements uninitialized, so if you wanted to initialized them to 0, use memset or a loop:

memset( g_device->name , '\0' , NAME_LENGTH * sizeof( char ) );

or:

for( size_t index = 0 ; index < NAME_LENGTH * sizeof( *g_device->name ) ; index++ )
{
    g_device->name[index] = '\0';
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use calloc to allocate the buffer, i.e.

g_device = calloc(1, sizeof(device_t));

This will allocate a buffer, which is completly filled with Zeroes, i.e. there's no need for further initialization of the character array.

2 Comments

Zeroes, not NULL. And the zeroes are interpreted like nul (\0). (nitpick)
You're right, my answer was imprecise at this point. I adapted the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.