c 结构体和 pthread 指针分配

标签 c pointers segmentation-fault structure

我正在做一项作业,我必须使用 pthreads C 处理一些图像。

我有以下结构:

typedef struct {
    int type;
    int width;
    int height;
    int max_value;
    int *input;
}image;

typedef struct {
    int id; // thread id
    image *in; //input image
}ptf_arguments;

我还有一个函数,我尝试实例化一个struct_b数组,并将给定struct_a的参数分配给每个函数

void resize(image *in, image * out) {
    int i;
    pthread_t tid[num_threads];
    ptf_arguments *arguments[num_threads];
    arguments[0]->in->input = (int *)malloc(in->width * in->height * sizeof(int));
    arguments[0]->in = in; // HERE

    printf("First thread should have id = %d. In image of (%d)\n", arguments[0]->id, arguments[0]->in->width); //here
    for(i = 0 ; i < num_threads; i++) {
        pthread_create(&(tid[i]), NULL, resize_thread_function, &(arguments[i]));
    }
}

1)我不太了解结构,我需要有人向我解释如何将输入/输出图像传递给我的 ptf_arguments 结构,以便我可以将其传递给 pthreads 函数。

2)我需要为图像结构分配内存吗?

3) 我是否需要为 ptf_arguments 结构的图像结构内的 int 数组分配内存?

谢谢

最佳答案

当我阅读代码时,我明白了

ptf_arguments *arguments[num_threads];
arguments[0]->in->undefined behavior

在取消引用之前,您需要将in指向有效的image结构。最简单的方法可能是将标记为 //HERE 的行移到上一行上方。

是的,您还需要分配一个int数组,并将image结构的input成员指向该内存。不用说,您需要为每个 ptf_arguments 对象(而不仅仅是第一个对象)进行初始化和分配。

我认为传递单个 ptf_arguments 对象的地址的语法很好。

关于c 结构体和 pthread 指针分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53065952/

相关文章:

c - 文件/程序范围内的二维数组

c++ - 在 C++ 程序中使用 C 库中定义的类型,命名空间类似于方案

c - c中的字符串比较

C中的循环函数指针问题

c - memcpy 在 strstr 成功后导致段错误

c - C 文件 IO 的奇怪行为

c - 交换单链表中的两个节点

c - 指针的地址和指针包含的地址之间的区别

c - 为什么下面会产生segmentation fault呢?

c++ - 为什么在向类内的数据 vector 插入元素时出现段错误?