mahesh
mahesh

Reputation: 17

To check if array value is NULL i.e. has been set or not

The array takes the garbage value if it is not initialized. To check whether the array is NULL we will use NULL or 0 to initialize the array while declaring.

If the user inserts the value 0 for an array say a[1]=0 and he didn't give the value for a[3] but both a[1] = 0 a[3] = 0.

Without initializing the array as NULL

 #include <stdio.h>
main(){
    int i, a[5];
    a[0] = 0;
    a[1] = 2;
    a[3] = 4;
    a[4] = 5;
    for (i = 0 ; i < 5 ; i++){
        printf("%d ", a[i]);
    }
}

here a[2] has some garbage value.

Initializing the array to NULL or 0

#include <stdio.h>

main() {
    int i, a[5] = {0};
    a[0] = 0;
    a[1] = 2;
    a[3] = 4;
    a[4] = 5;
    for (i = 0 ; i  <5 ; i++) {
        printf("%d ", a[i]);
    }       
}

Here a[2] is not inserted but it takes the value 0

If the user's input is 0 (here a[0] = 0) then how can he actually know whether the value is inserted or not

Upvotes: 0

Views: 1327

Answers (1)

Superlokkus
Superlokkus

Reputation: 5039

Problematic first is that you seem to have a misunderstanding about NULLand 0. In C NULL is usually the number 0, but made to something that fits to any type. So, although you shouldn't rely on it nor use it at all, int i = NULL is the same as int i = 0. And this leads to the general problem:

Convention of a "NULL"/"OPTIONAL"/"NIL"/"NOT_SET" value

For pointers this can easily be done by setting them to NULL, since a valid pointer will have any value, but NULL. Doing this for normal types, like int, is not natively possible, because if int can be all integers / Z where do you want to put your "exceptional" value?! That's the reason why often pointers, instead of the direct types, are used, or some more fancy stuff like boost optional in C++.

So you would have to write something like:

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

#define ARRAY_SIZE 5

int main (void)
{
    int number = 42;
    int *array[ARRAY_SIZE] =  {0};

    array [2] = &number;

    int i;
    for (i = 0; i < ARRAY_SIZE; i++){
        if (array[i] != NULL){
            printf("Position %d was set to %d\n",i,*array[i]);
        }
    }

    return 0;
}

However be cautious when using the address of auto ("stack") variables, usally you will have to use dynamic variables, i.e. use malloc and free.

Upvotes: 1

Related Questions