【问题标题】:Modify content using pointers使用指针修改内容
【发布时间】:2015-10-16 16:04:40
【问题描述】:

我有一个练习,我必须创建一定数量的 pthread 来对图像进行降噪,但我的指针有问题。每个线程都获取 input_image,但随后所有线程都需要能够写入相同的 output_image。以下是相关的部分。

struct task{
    int start_row, stop_row, window_size;
    image_matrix input_image;
    image_matrix * output_image; //holds the address of the original output_matrix
};

void* func( void* arg ){
    task* t_arg = ( task* )arg;

    image_matrix& input = t_arg->input_image;

    //image_matrix& output = t_arg->output_image; 
    image_matrix * matrix_address= t_arg->output_image; //<-----

    for(int y = start; y<=stop; y++){
        for(int x=0;x<input.get_n_cols();x++){
            float filtered_value = median_filter_pixel(input, y, x, window_size);
            *matrix_address.set_pixel(y,x,filtered_value); //<------2
        }
    }
    pthread_exit( NULL );
}


    //This is how I set the output_image in main() but I'm pretty sure
    //this is good.  Filtered image is just   
    td[j].output_image = &filtered_image;

这给出了下面的错误,但我不明白为什么。 matrix_address 指向的值是 image_matrix 类型,因此它应该具有 image_matrix 的所有属性。我已经尝试了所有对我有意义的方法,但没有任何效果。此外,当我从标记为 2 的行中删除取消引用运算符时,它会给出同样的错误,这对我来说也没有意义。

request for member ‘set_pixel’ in ‘output_address’, which is of pointer
    type ‘image_matrix*’ (maybe you meant to use ‘->’ ?)

【问题讨论】:

  • Pthreads 在 2011 年之前是如此...
  • 老实说,甚至不用pthreads。您看到的错误类型清楚地表明任何线程的想法都超出了您的水平。对不起。
  • 我有一种强烈的感觉,你的 output_image 会损坏
  • 我必须使用线程进行练习哈哈。这是我对他们的第一次介绍。

标签: c++ pointers dereference


【解决方案1】:

在 C++ 中,通过. 的成员访问和函数调用() 都比通过* 的指针解引用绑定更紧密。也就是说,代码被解析为:

*((matrix_address.set_pixel)(y, x, filtered_value))

当然,matrix_address 是一个指针,因此它没有可访问的成员。您需要引入括号:

(*matrix_address).set_pixel(y, x, filtered_value)

当然,这样写起来会非常乏味。这就是为什么 C++ 有一个“访问指针的成员操作符”,-&gt;

matrix_address->set_pixel(y, x, filtered_value)

【讨论】:

  • OMG 如此简单的解决方案解决了我一直坚持很长时间的问题。它有效并且没有损坏。谢谢。
猜你喜欢
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多