结构和指针的C错误

时间:2013-10-21 13:48:03

标签: c pointers struct

typedef struct stnode {
    unsigned number;
    char * name;
    unsigned section;
    struct stnode * next;
} StudentNode; 

void buildStudentSections(StudentNode * sections[], StudentNode students[], size_t num_students) {

        if(!num_students) return ;
        StudentNode * aux=NULL;

        for(int i=0;i<num_students;i++){

            aux=sections[students[i].section];
            (**(sections+students[i].section)).next=*(students+i);


            }   

    }

当我尝试执行此代码时出现此错误:

incompatible types when assigning to type ‘struct stnode *’ from type ‘StudentNode’

代码有什么问题,我已经尝试了很多东西,但是没有用过。我只想推荐下一个我正在分析的“学生”

3 个答案:

答案 0 :(得分:2)

阅读编译器错误(您尚未执行此代码 - 它尚未编译...)

  来自'StudentNode'类型的

'struct stnode *'

基本上你正在尝试为指针分配一个结构,这不起作用。请看以下行:

(**(sections+students[i].section)).next=*(students+i);

问题出在(students + 1) de-reference

答案 1 :(得分:1)

问题是*(students+i)正在取消引用元素students+i。它应该是:

(**(sections+students[i].section)).next=students+i;

答案 2 :(得分:0)

改变这个:

void buildStudentSections(StudentNode * sections[], StudentNode students[], size_t num_students) {

        if(!num_students) return ;
        StudentNode * aux=NULL;

        for(int i=0;i<num_students;i++){

            aux=sections[students[i].section];       // = *(x) you are dereferencing students+1
            (**(sections+students[i].section)).next=*(students+i);


            }   

    }

对此:

void buildStudentSections(StudentNode * sections[], StudentNode students[], size_t num_students) 
{

        if(!num_students) return ;
        StudentNode * aux=NULL;

        for(int i=0;i<num_students;i++)
        {

            aux=sections[students[i].section];      //removed '*`
            (**(sections+students[i].section)).next = (students+1); 


        }   

}