我首先會說,這主要是由於我對指針的理解不夠。我在下面的函數遇到麻煩:從C++中刪除一個項目時,簡單的指針問題
//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;
}
這裏就是我想這樣做:我想從緩衝區中獲取該指針的值,並將其放在一個指針中。這樣,變量項目將包含緩衝區中的指示值。然後,我將它設置爲NULL,所以它現在是空的。
我無法在指針中存儲該指令的值。它會按照現在寫入的方式導致分段錯誤。我認爲說* item = temp會將item指向的位置的值設置爲temp的值。但是,我認爲它將它設置爲temp的內存位置,因此我得到了分段錯誤。
'NULL'應用於指針,而不是整數。 – Barmar
我們無法確定'buffer'的類型是什麼,或者'position_to_consume_in_buffer'最初設置爲什麼或者它如何改變(推測它是一個整數)。如果使用錯誤的索引,則會導致段錯誤,並且如果「緩衝區」不是雙指針,那麼您正在以可能會出現段錯誤的方式訪問它。 – spiffman
顯示您如何調用該功能。也許你沒有傳遞一個有效的指針。 – Barmar