繁体   English   中英

在函数 pthread 中访问结构变量

[英]Accessing struct variables in a function pthread

在 pthread_creation 调用的函数中访问结构变量的正确方法是什么。 这就是我想要做的

void *add_first_quat(void *a){
    struct thread1Struct *myArray = (struct thread1Struct *)a;  
    int i ;
    for(i= *myArray>start; i < *myArray>end; i++){
        sum+= *myArray>th1Array[i];
    }

    /* the function must return something - NULL will do */
    return NULL;
}

在我的结构中,我定义了两个变量和指向全局定义数组的指针

struct thread1Struct{

    int start = 0;
    int end = 25;

    int *th1Array = myArray;

};

这就是我调用 pthread_create 函数的方式

(pthread_create(&inc_first_quater_thread, NULL, add_first_quat, (void*) &th1StrObj))

为什么我的代码不起作用? 我收到以下错误

main.c: In function ‘add_first_quat’:
main.c:14:9: error: dereferencing pointer to incomplete type
  for(i= *myArray>start; i < *myArray>end; i++){
         ^
main.c:14:18: error: ‘start’ undeclared (first use in this function)
  for(i= *myArray>start; i < *myArray>end; i++){
                  ^
main.c:14:18: note: each undeclared identifier is reported only once for each function it appears in
main.c:14:29: error: dereferencing pointer to incomplete type
  for(i= *myArray>start; i < *myArray>end; i++){
                             ^
main.c:14:38: error: ‘end’ undeclared (first use in this function)
  for(i= *myArray>start; i < *myArray>end; i++){
                                      ^
main.c:15:9: error: dereferencing pointer to incomplete type
   sum+= *myArray>th1Array[i];
         ^
main.c:15:18: error: ‘th1Array’ undeclared (first use in this function)
   sum+= *myArray>th1Array[i];
                  ^
main.c: At top level:
main.c:34:12: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
  int start = 0;
            ^

第一个问题(语法):

尝试myArray->start(*myArray).startmyArray[0].start 在这种情况下,第一种语法将是我的偏好。

第二个问题:

dereferencing pointer to incomplete type

在引用任何字段之前,您需要提供完整的声明。 通过将结构的完整声明移动到代码文件的顶部来解决问题,或者将它放在一个.h文件中,在所有使用该结构的源文件中#include

这个: *myArray>start不是访问结构指针成员的正确语法。

您可以这样做: (*myArray).start ,它取消引用指针,因此*myArraystruct thread1Struct类型,然后使用. 用于会员访问。

首选方法是myArray->start ,其中->运算符对指向结构的指针进行成员访问。

问题在于您访问结构元素的方式。 您的表达式*myArray>start对编译器毫无意义。 如您所知, myArray是指向struct的指针。 您可以通过两种方式访问​​数据成员:

  1. 您可以使用间接运算符(例如(*myArray).start
  2. 您可以使用箭头运算符(例如myArray->start

这是您访问任何结构指针的数据成员的方式 它不仅仅与 p 线程有关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM