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'};
}
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';
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments