Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer pointing to an empty array

Tags:

arrays

c

pointers

I have a pointer that is pointing to the start of an array, but I need to check that it is unallocated. I thought of dereferencing the pointer and checking if NULL but that leads to a type error. Can anyone see what I'm doing wrong?

int mydispose(int *array){
    int i = 0;

    if(*array == NULL){
            return 1;
    }

    return ;

}

EDIT: Sorry if I was unclear: I have a pointer that points to the start of an array, but I wish to check whether the array is empty.

like image 746
Alex Avatar asked Nov 08 '10 16:11

Alex


People also ask

Can a pointer point to an array?

Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.

Is array 0 a pointer?

An array is a pointer, and you can store that pointer into any pointer variable of the correct type. For example, int A[10]; int* p = A; p[0] = 0; makes variable p point to the first member of array A.

Are pointers initialized to null?

A pointer can also be initialized to null using any integer constant expression that evaluates to 0, for example char *a=0; . Such a pointer is a null pointer. It does not point to any object.

Does a pointer to an array point to the first element?

This pointer points to the first element in the array. You can dereference that pointer to access the array element. Pointer variables that point into an array can also be moved around in the array via the pointer increment and decrement operations.


2 Answers

*array == NULL is wrong. You are dereferencing the pointer first (which could lead to a segfault if the pointer really is null) and then comparing its int value to a pointer value. Moreover, your compiler will perfectly accept that erroneous expression if NULL is defined as just 0 and not (void *) 0.

You should be checking array == NULL to see if the passed pointer refers to anything, and then dereference it only in case it's not NULL.

Be aware, however, that dereferencing a non-null pointer isn't guaranteed to be a safe operation either. If the pointer contains a garbage value because it was allocated on the stack and not initialized, or if it refers to a deallocated region of memory, nasty bugs can happen.

like image 186
Blagovest Buyukliev Avatar answered Sep 28 '22 12:09

Blagovest Buyukliev


You want if (array == NULL) -- but unless you first initialize array to NULL, it won't do any good either. I think you'd be better off backing up and telling us a bit more about what you're trying to accomplish, and trying to get help trying to accomplish your overall goal.

like image 27
Jerry Coffin Avatar answered Sep 28 '22 12:09

Jerry Coffin