开发者

C Structure Pointer Problem

I have this struct;

#define BUFSIZE 10
struct shared_data {
    pthread_mutex_t th_mutex_queue;
    int count;

    int data_buffer_allocation[BUFSIZE];
    int data_buffers[BUFSIZE][100];
开发者_如何转开发};

and I want to allocate one of the data_buffers for a process, for that purpose I execute the following function;

int allocate_data_buffer(int pid) {
    int i;
    for (i = 0; i < BUFSIZE; i++) {
        if (sdata_ptr->data_buffer_allocation[i] == NULL) {
            sdata_ptr->data_buffer_allocation[i] = pid;
            return i;
        }
    }
    return -1;
}

but the compiler warns me that I'm comparing pointer to a value. When I put a & in front of sdata_ptr it calms down but I'm not sure if it will work. Isn't what I wrote above supposed to be true?


Probably because NULL is #define'd to be (void*)0 which means

 if (sdata_ptr->data_buffer_allocation[i] == NULL) {

would be comparing an int to a pointer. Change it to compare to 0 instead.


NULL is "null pointer", but data_buffer_allocation is an array of int. You should compare to 0:

    if (sdata_ptr->data_buffer_allocation[i] == 0) {


Since you don't have an array of pointers, comparisons to NULL are improper (although they will end up resolving to 0).

For the comparison to be valid, you will want to compare directory to zero. However, please keep in mind that the acquisition of your array does NOT initialize values, so you will have random garbage in your array to start with. As a result, comparing to zero (unless you have initialized your values to zero elsewhere) will be inconsistent and useless.

Also, it may be nitpicky, but when I hear a method/function like allocate_data_buffer I think of resource acquisition, such as requiring a new or new[]. Your method name, and use of NULL and such seem to indicate that this code was initially intended to actually use pointers for this allocation, but perhaps was modified. For the modification to be 'complete' in my opinion, I would continue by creating a proper initialization and method names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜