user2995743
user2995743

Reputation: 99

How to make an array of pointer to NULL in C?

I had similar code in my project

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

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

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

and I had a condition in source code like this

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

I want to test the FALSE decision of the above condition ( ie test_ptr == NULL ) For this I had tried different methods but not succeeded yet, please help me to resolve this

Upvotes: 0

Views: 72

Answers (1)

ikegami
ikegami

Reputation: 386541

As defined, test_ptr can't ever be NULL. test_ptr is an array, not a pointer. It does degenerate into a pointer (which is to say it's implicitly converted into a pointer) when treated as a pointer, but not one that is NULL.

I think you want

TEST* test_ptr = NULL;

You can still use the [] indexing notation because

p[i]

is just another way of saying

*(p+i)

which actually expects a pointer.

Demonstration:

#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;
}

Upvotes: 3

Related Questions