C结构体指针问题

标签 c pointers 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];
};

我想为一个进程分配一个 data_buffer,为此我执行以下函数;

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

但编译器警告我,我正在将指针与值进行比较。当我在 sdata_ptr 前面放一个 & 时,它会平静下来,但我不确定它是否会起作用。我上面写的不是应该是真的吗?

最佳答案

可能是因为 NULL 被#define 定义为 (void*)0 这意味着

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

会将 int 与指针进行比较。将其更改为与 0 进行比较。

关于C结构体指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2571478/

相关文章:

c - Security.h 中结构的 macOS 文档

C 指针 : what's the difference between struc* A, struct *A 和 struct * A?

c++ - 在另一个结构中声明内部结构导致错误 : invalid use of struct

c# - 按位相等

重定位 vector 表的C代码

c - 无法使用 APDU 命令从 Contact VISA 卡读取信息

c++ - 带有指向对象初始化的指针的数组

pointers - golang 和指针接收器中的自定义错误

c# - 有没有办法知道是什么让对象在 C# 中保持事件状态

c++ - libuv - 如何保持默认循环运行直到程序中的至少一个线程处于事件状态?