0

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

0

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.