繁体   English   中英

如何在 C 中创建指向 NULL 的指针数组?

[英]How to make an array of pointer to NULL in C?

我的项目中有类似的代码

typedef struct
{
int a;
int b;
int c;
}TEST;

TEST test[2] = 
{
  {1,2.3}
, {3,4,5}
};

TEST *test_ptr[2] = 
{
 test,
 test
};

我在源代码中有这样的条件

if ( test_ptr != NULL )
{
    do_something();
}

我想测试上述条件的 FALSE 决定(即 test_ptr == NULL )为此我尝试了不同的方法但还没有成功,请帮我解决这个问题

根据定义, test_ptr永远不能为NULL test_ptr是一个数组,而不是指针。 当被视为指针时,它确实退化为指针(也就是说它被隐式转换为指针),但不是 NULL。

我想你想要

TEST* test_ptr = NULL;

您仍然可以使用[]索引符号,因为

p[i]

只是另一种说法

*(p+i)

这实际上需要一个指针。

示范:

#include <stdio.h>

typedef struct {
   int a;
   int b;
   int c;
} Test;

static Test tests_arr[] = {
   { 1, 2, 3 },
   { 3, 4, 5 },
};

int main(void) {
   printf("%d\n", tests_arr[1].b);                           // 4
   printf("%d\n", (tests_arr+1)->b);                         // 4
   printf("%d\n", (&(tests_arr[0])+1)->b);                   // 4

   Test* tests_ptr = NULL;
   printf("%s\n", tests_ptr == NULL ? "NULL" : "Not NULL");  // NULL

   tests_ptr = test_arr;
   printf("%s\n", tests_ptr == NULL ? "NULL" : "Not NULL");  // Not NULL
   printf("%d\n", tests_ptr[1].b);                           // 4
   printf("%d\n", (tests_ptr+1)->b);                         // 4

   tests_ptr = &(test_arr[0]);
   printf("%s\n", tests_ptr == NULL ? "NULL" : "Not NULL");  // Not NULL
   printf("%d\n", tests_ptr[1].b);                           // 4
   printf("%d\n", (tests_ptr+1)->b);                         // 4

   return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM