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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4178804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:03:41  来源:igfitidea点击:

How to see if an element is null in an array in C?

c

提问by Alex

How can I check to see if an element in an array is empty in C?

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

if(array[i] == NULL) 

Doesn't seem to work.

似乎不起作用。

回答by peoro

What do you mean with empty?

你说的是什么意思?

When a C program is executed, variables that you don't explicitly initialize have got unpredictable values.

执行 C 程序时,您未显式初始化的变量具有不可预测的值。

You need to set all of your array cells to NULL (or to 0, or to whatever value represents emptyness in your program logic) and then you can check it in the way you did:

您需要将所有数组单元格设置为 NULL(或设置为 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"
  }
}

回答by Billy ONeal

Question answer:

问题解答:

What you posted is the correct code.

您发布的是正确的代码。

Elaboration:

细化:

If it "doesn't seem to work", perhaps the problem does not lie at this location in your code. If you would post a more complete example of what you have, the code's expected behavior and actual behavior, we may be able to help you.

如果它“似乎不起作用”,那么问题可能不在于代码中的这个位置。如果您想发布一个更完整的示例来说明您所拥有的内容、代码的预期行为和实际行为,我们或许可以为您提供帮助。

回答by icecrime

Assuming that arrayis indeed an array of pointers, the single line of code provided should indeed verify that element at index iis NULL.

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

Note however that if you array is not properly initialized (ie: provide an initial value to each cell), the array most probably contains garbage and your condition will most probably end up being false.

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

回答by J.M.I. MADISON

At first I was thinking, "They need to use pointer arithmetic so the object doesn't get auto de-referencedby the "[ ]"operator.

起初我在想,“他们需要使用指针算术,这样对象就不会被 “[]”运算符自动取消引用

Then I realized, no... Arrays in C don't have null slots.

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

I conclude, the asker is:

我得出结论,提问者是:

  1. Using an array of structs.

  2. Using it as if it were an array of pointers to structs.

  1. 使用结构数组。

  2. 使用它就好像它是一个指向结构的指针数组。

peoro's solutionis pretty good. But I would recommend modifying it a bit. Add a ".exists" property to your struct if you want to do it the lazy/simple way. Simple is not a bad thing, the more parts in a machine the more things that can go wrong.

peoro的解决方案非常好。但我建议稍微修改一下。如果您想以懒惰/简单的方式进行操作,请将“.exists”属性添加到您的结构中。简单并不是一件坏事,机器中的零件越多,可能出错的东西就越多。

Code below demonstrates two things:

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

  1. Faking a sparse arrayusing peoro's solution with .exists flag modification.

  2. An actual sparse arrayusing double pointers.

  1. 使用带有 .exists 标志修改的 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]
*** ****************************************** **/

While I am 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 put this into it. Double click the script to run it, or use "./NAE.SH" where it resides in your git bash terminal.

当我在做的时候。如果要从命令行运行,请将文件命名为:“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 ] ##
##################################################

This is C99code by the way. I try to write it avoiding any C99 specific features though.

顺便说一下,这是C99代码。我尝试编写它避免任何 C99 特定功能。