Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing array element to NULL [closed]

Tags:

arrays

c

null

How to initialise an element of array to NULL.For example if I have char *array[10]; I want last element to be NULL, so that I can pass this array to execv

like image 667
Nazerke Avatar asked Nov 08 '12 16:11

Nazerke


People also ask

Can you initialize an array to null?

Array elements are initialized to 0 if they are a numeric type ( int or double ), false if they are of type boolean , or null if they are an object type like String .

How do you initialize a char array to null?

You can't initialise a char array with NULL , arrays can never be NULL . You seem to be mixing up pointers and arrays. A pointer could be initialised with NULL . char str[5] = {0};

How do you initialize an array of elements to zero?

The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.

Can an array be set to null in C?

If you have a char[] , you can zero-out individual elements using this: char arr[10] = "foo"; arr[1] = '\0'; Note that this isn't the same as assigning NULL , since arr[1] is a char and not a pointer, you can't assign NULL to it.


2 Answers

To initialise an array of char* to all NULLs:

char* array[10] = { NULL }; /* The remaining elements are implicitly NULL. */

If you want to provide initial elements for execv():

char* array[10] = { "/usr/bin/ls", "-l" }; /* Again, remaining elements NULL. */

or if you wish to omit the dimension from the array declaration:

char* array[] = { "/usr/bin/ls", "-l", NULL };
like image 108
hmjd Avatar answered Oct 17 '22 14:10

hmjd


NULL is nothing but : #define NULL (void*) 0 UL The NULL you are talking about is nul character which is '\0'

see man execv page or other exec processes .. it's actually take variable number of arguments

like image 31
Omkant Avatar answered Oct 17 '22 12:10

Omkant