访问函数pthread中的结构变量



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

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;
            ^

第一个问题(语法):

Try myArray->start or (*myArray).start or myArray[0].start。在本例中,我更倾向于使用第一种语法。

第二个问题:

dereferencing pointer to incomplete type

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

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

你可以这样做:(*myArray).start,它解引用指针,使*myArray的类型为struct thread1Struct,然后使用.进行成员访问。

首选的方法是myArray->start,其中->操作符对指向struct的指针进行成员访问。

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

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

这是访问任何结构指针的数据成员的方式。

最新更新