代码之家  ›  专栏  ›  技术社区  ›  Alex

如何查看C中数组中的元素是否为空?

c
  •  8
  • Alex  · 技术社区  · 15 年前

    如何检查C中数组中的元素是否为空?

    if(array[i] == NULL) 
    

    好像没用。

    3 回复  |  直到 15 年前
        1
  •  19
  •   peoro    15 年前

    你什么意思 空的 ?

    当执行C程序时,未显式初始化的变量会得到不可预测的值。

    您需要将所有数组单元格设置为空(或设置为0,或设置为任何表示程序逻辑中为空的值),然后您可以按以下方式进行检查:

    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"
      }
    }
    
        2
  •  1
  •   Billy ONeal IS4    15 年前

    问题答案:

    你发布的代码是正确的。

    阐述:

    如果它“看起来不起作用”,也许问题不在代码中的这个位置。如果您想发布一个更完整的示例,说明您所拥有的代码的预期行为和实际行为,我们可能会帮助您。

        3
  •  1
  •   icecrime    15 年前

    假设 array 确实是一个指针数组,所提供的单行代码应该确实验证索引处的元素 i 为空。

    但是,请注意,如果数组未正确初始化(即:为 每个单元 ),数组很可能包含垃圾,并且您的条件很可能最终为false。

        4
  •  0
  •   KANJICODER    7 年前

    一开始我在想, “他们需要使用指针算术,所以 对象无法获取 自动取消引用 "[ ]" 接线员。

    然后我意识到,不。。。 C中的数组没有 空插槽 .

    我的结论是,提问者是:

    1. 使用结构数组。

    2. 把它当作一个数组 指向结构的指针。

    皮罗溶液 很不错。但我建议你修改一下。 如果你想用懒惰/简单的方式来添加一个“.En存在”属性。 简单并不是坏事,一台机器的零件越多,就越可能出错。

    下面的代码演示了两件事:

    1. 伪造稀疏阵列 使用PEORO的解决方案。存在标志修改。

    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's 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's 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]
    *** ****************************************** **/
    

    当我在做的时候。如果要从命令行运行,请命名文件: “NAE.C99”,然后创建一个名为“NAE.SH”的bash文件并将其放入其中。 双击脚本以运行它,或者在脚本所在的位置使用“./NAE.SH” git bash终端。

    ##################################################
    ############################# 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 ] ##
    ##################################################
    

    这是 C99型 顺便说一句。不过,我尽量避免使用任何C99特定的特性。