How to find out if an element is null in an array in C?

How to check if an element is in an array in C?

if(array[i] == NULL) 

It doesn't seem to work.

+10
source share
4 answers

What do you mean with a blank?

When program C runs, variables that you did not explicitly initialize received unpredictable values.

You need to set all cells in the array to NULL (or 0 or any value representing a void in your program logic), and then you can check it the way you did it:

int *array[3] = { NULL, NULL, NULL }; // array of three "empty" pointers

...

for( i = 0; i < 3; ++ i ) {
  if( array[i] == NULL ) {
    // i-th cell is "empty"
  }
}
+16
source

The answer to the question:

What you submitted is the correct code.

Development:

" ", , . , , , .

+1

, array , , i NULL.

, ( : ), , , , , , .

+1

: " , " [] ".

, ... C .

, :

  1. .

  2. , .

Peoro . . ".exists" , / . - , , .

:

  1. peoro .exists.

  2. .


#include<stdlib.h> //:for: malloc(...)
#include<stdlib.h> //:for:   free(...)
#include <stdio.h> //:for: printf(...)
int main( void ){
    printf("[BEG:main]\n");

    typedef struct MyStruct{
        int whatever;
    } MyStruct;

    int        num = 16; //:sixteen_elements

    //:USE CALLOC HERE! If you use malloc you'll
    //:end up with something even worse than
    //:null pointers... Pointers that point to
    //:random places in memory. 
    //:
    //: It will make your:
    //: if( arr[i] != NULL )... 
    //: look before you leap check worthless.
    MyStruct** arr =(
        calloc(
            1 //:allocating 1 item: arr

            //:Amount of memory taken up by
            //:all 16 MyStruct pointers in array.
        ,   sizeof(MyStruct*)*num
        )
    );;

    //:Initialize only the EVEN slots:
    for(int i = 0; i < num; i+=2 ){
        //:Create new MyStruct in slot i,
        //:initialized with junk data.
        arr[i]= malloc(sizeof(MyStruct));
    };;

    //:If element not null, set it whatever:
    for(int i = 0; i < num; i++){
        if(NULL != arr[i]){
            arr[i] -> whatever = i;
        };;
    };;

    //:Loop and print to confirm:
    for(int i = 0; i < num; i++){
        if(NULL != arr[i]){
            printf("whatever: %d\n", arr[i] -> whatever);
        };;
    };;

    //:ALTERNATIVELY:
    //:If we were going to use peoro method,
    //:I would advise adding a ".exists" flag
    //:to your struct.

    typedef struct DoublePointersAreTooMuchWork{
        int exists;

        //:Because we are going to use malloc this
        //:time, we have no guarantee what this
        //:value will be. but you will probably
        //:see all of them == 0. If you set
        //: num=1000 you'll probably see a non-zero
        //: entry somewhere. But, no guarantees!
        int mystery_value;
    } MyStruct02;

    MyStruct02* arr2 = malloc(sizeof(MyStruct02)*num);
    for(int i = 0; i < num; i++ ){

        if( i%2 ){ //:evens
            arr2[i].exists = 1;
        }else{
            arr2[i].exists = 0;
        };;
    };;

    for(int i = 0; i < num; i++ ){
        if( arr2[i].exists ){
            printf("Exists:val:%d\n", arr2[i].mystery_value);
        }else{
            printf("[Pretend_I_Dont_Exist]\n");
        };
    }

    printf("[END:main]\n");
} //[[main]____________________________________]//

/** ****************************************** ***
OUTPUT:
[BEG:main]
whatever: 0
whatever: 2
whatever: 4
whatever: 6
whatever: 8
whatever: 10
whatever: 12
whatever: 14
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[Pretend_I_Dont_Exist]
Exists:val:0
[END:main]
*** ****************************************** **/

While I'm at it. If you want to run from the command line, name the file "NAE.C99", then create a bash file called "NAE.SH" and paste it into it. Double-click the script to run it, or use "./NAE.SH" where it is located in your git bash terminal.

##################################################
############################# SC[ hkmf-strict ] ##
##################################################
base_name_no_extension="NAE"
##################################################
MY_COMMAND_STRING=$(cat << GCC_COMMAND_01
    gcc                                     
    -x c                                    
    -c $base_name_no_extension.C99          
    -o my_object_file.o                     
    -m64                                    
GCC_COMMAND_01
)                                       
C=$MY_COMMAND_STRING  ############################
C=$C"-Werror        " ## WarningsAreErrors      ##
C=$C"-Wfatal-errors " ## StopAtFirstError       ##
C=$C"-Wpedantic     " ## UseStrictISO_C         ##
C=$C"-Wall          " ## WarnAboutAnyWeirdCode  ##
C=$C"-Wextra        " ## "-Wall" WarningsExtra  ##
C=$C"-std=c99       " ## VersionOf_C_ToUse      ##
MY_COMMAND_STRING=$C  ############################

echo $MY_COMMAND_STRING
     $MY_COMMAND_STRING

C1=" gcc -o EXE.exe my_object_file.o "    
C2=" ./EXE.exe                       "    
C3=" rm my_object_file.o             "    
C4=" rm EXE.exe                      "  
$C1 && echo "OK:"$C1 || "FAIL:$C1"
$C2 && echo "OK:"$C2 || "FAIL:$C2"
$C3 && echo "OK:"$C3 || "FAIL:$C3"
$C4 && echo "OK:"$C4 || "FAIL:$C4"
##################################################
read -p "[END_OF_BUILD_SCRIPT:PressAnyKey]:"
##################################################
############################# SC[ hkmf-strict ] ##
##################################################

By the way, this is the code C99 . I am trying to write this while avoiding any particular features of the C99 though.

0
source

All Articles