从缓冲区中删除项目时 C++ 中的简单指针问题

Simple pointer troubles in C++ when removing an item from a buffer

首先我会说这主要是因为我对指针的理解不够。我在以下功能中遇到问题:

//remove item function:

int remove_item(buffer_item * item) {
   buffer_item temp = buffer[position_to_consume_in_buffer];
   if (temp == NULL) {
      return -1;
   }
   else {
      *item = temp; //***How do I do this properly?
   }

   buffer[position_to_consume_in_buffer] = NULL;
   position_to_consume_in_buffer = (position_to_consume_in_buffer+1)%BUFFER_SIZE;
   return 0;
}

buffer_item的定义:

/* buffer.h */
#ifndef BUFFER_H
#define BUFFER_H

typedef int buffer_item;
#define BUFFER_SIZE 7

#endif

最后,我从哪里调用函数:

//consumer thread:
void *consumer(void *param) {
    buffer_item * rand;
    unsigned int consumerseed = (unsigned int)pthread_self();
    while (1) {
    //sleep for a random period of time:    
    int consumersleeptime = rand_r(&consumerseed)%600+200;
    usleep(consumersleeptime);
    //wait on both semaphores
    sem_wait(&full);
    int check = pthread_mutex_lock (&mutex);
    if (check != 0) {
        printf("Check was not equal to zero for locking mutex in consumer. \n"); }
    //attempt to remove an item from buffer:
    int p = remove_item(rand);
    if (p == -1) {
        printf("Error encountered calling remove_item from consumer. \n"); 
    }
    int consumed = *rand;
    printf("Consumer consumed an item %d from the buffer. \n", consumed);
    //signal both semaphores
    check = pthread_mutex_lock (&mutex);
    if (check != 0) {
        printf("Check was not equal to zero for unlocking mutex in consumer. \n"); }
    sem_post(&empty);
    }
    return NULL;
}

这是我想要做的:我想从缓冲区中获取该索引的值,并将其放在一个指针中。这样,变量 item 将包含缓冲区中索引的值。然后我将我们消耗的那个索引设置为 NULL,所以它现在是空的。

我无法在我的指针中存储该索引的值。它按照现在的编写方式导致分段错误。我认为说 *item = temp 会将 item 指向的位置的值设置为 temp 的值。但是,我认为它是将它设置为 temp 的内存位置,因此我遇到了分段错误。

您正在声明指针 rand,但从未对其进行初始化。结果,remove_item 试图通过这个未定义的指针间接访问,

您可以只声明一个普通变量,并将其地址传递给 remove 函数:

buffer_item consumed;
int p = remove_item(&consumed);