Struct as incompatible pointer type in C

2019-09-04 05:57发布

I have created a struct with only 1 member and the only thing I want to is:

  1. Pass the struct to the function updateDispCase
  2. Update the member StartTime inside and outside the scope.

The problem I face is that I get a error "Passing argument of updateDispCase from incompatible pointer type". If I try to uncomment "//dispCaseAr[iNumber]->StartTime = 10;" the program crashes.

How do I pass my struct to the function and how to I update it?

My code is shown below:

#include <stdio.h>
#define NROFDISPCASE 4

typedef struct {
int nr;
double StartTime;
} DispCase;

DispCase dispCaseArray[NROFDISPCASE];

//Preprocessor
void updateDispCase(DispCase *dispCaseAr[],int);
//

int main(){
    int i;

    int value1[NROFDISPCASE]={1,2,3,4};                  // Display nr.

    //Initialize DisplayCase
    for(i = 0; i<NROFDISPCASE; i++){
        dispCaseArray[i].StartTime = value1[i];
    }

    updateDispCase(&dispCaseArray,0);
    printf("%f\n",dispCaseArray[0].StartTime);

    return 0;

}

void updateDispCase(DispCase *dispCaseAr[],int iNumber){
    //dispCaseAr[iNumber]->StartTime = 10;
}

1条回答
来,给爷笑一个
2楼-- · 2019-09-04 06:27

I solved the problem myself and I thought it would be an idea to write the answer to my problem. I removed the & from the function call and removed the brackets [] from the function. The new code is as follows: I forgot an array is always a pointer.

#include <stdio.h>
#define NROFDISPCASE 4

typedef struct {
int nr;
double StartTime;
} DispCase;


//Preprocessor
void updateDispCase(DispCase *dispCaseAr[],int);
//

int main(){
    DispCase dispCaseArray[NROFDISPCASE];
    int i;

    int value1[NROFDISPCASE]={1,2,3,4};                  // Display nr.

    //Initialize DisplayCase
    for(i = 0; i<NROFDISPCASE; i++){
        dispCaseArray[i].StartTime = value1[i];
    }

    updateDispCase(dispCaseArray,0);
    printf("%f\n",dispCaseArray[0].StartTime);

    return 0;

}

void updateDispCase(DispCase *dispCaseAr,int iNumber){
    dispCaseAr[iNumber]->StartTime = 10;
}
查看更多
登录 后发表回答