在条件中使用数组

Nas*_*Ohi 3 c arrays

我想检查条件中的数组.我们来看下面这个简单的代码:

#include <stdio.h>
int main()
{
    int array[] = {1,2,3,4,5}; // initializing an array
    if(array[] == {1,2,3,4,5}) // using as condition
    {
         printf("worked");
    }
    else printf("not worked");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误:

In function 'main':|
C:\Python32\Untitled4.c|5|error: expected expression before ']' token|
||=== Build finished: 1 errors, 0 warnings ===|
Run Code Online (Sandbox Code Playgroud)

那么我应该如何在条件中使用数组呢?

pb2*_*b2q 5

This format:

int array[]={1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)

Can only be used in the initialization or arrays or structs. This is referred to as aggregate initialization. This can't be used to generally represent an array.

Furthermore, you can't use == to compare arrays or structs in C.

要对您的条件进行编码,您需要检查每个值。


Jen*_*edt 5

如果您有一个现代的C编译器,至少是C99,您可以使用复合文字和函数来进行比较:

if(memcmp(array, (int[]){1,2,3,4,5}, sizeof array) == 0) {
   printf("worked");
}
Run Code Online (Sandbox Code Playgroud)
  • 这里memcmp(内存比较)比较两个指针所指向的数据.
  • (int[]){1,2,3,4,5}是复合文字,有类型的东西,()然后是{ }你的变量声明中的初始化器.
  • 当像这样的表达式一样使用时,这两个数组被转换为指向它们的第一个元素的指针

编辑:正如Eric正确评论的那样,memcmp如果数组的基类型(此处为int)没有填充位或字节,则只是有效的比较.因为现在int这种情况并不常见,所以我所描述的在通常的平台上都很好.如果有一天你有其他更复杂的数据类型,则必须为该类型的数组编写自己的比较函数.

  • memcmp不是一种安全的比较方法,因为即使是基本类型也可能有填充位.这适用于通用平台上的基本类型数组,但一般不是标准C,不可移植,不可移植,并且不适用于复杂类型(带填充的结构). (4认同)