【问题标题】:C error with structs and pointers结构和指针的 C 错误
【发布时间】:2013-10-21 13:48:03
【问题描述】:
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’

代码有什么问题,我已经尝试了很多东西,但没有奏效。我只想将下一个指向我正在分析的“学生”

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

    阅读编译器错误(你还没有执行这段代码——它还没有编译...)

    来自“StudentNode”类型的“struct stnode *”

    基本上,您正在尝试将结构分配给指针,这是行不通的。看下面一行:

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

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

    【讨论】:

    • 现在我收到错误第 7 行:1961 Segmentation fault 为什么?
    • 我们无法回答这个问题,您需要 debug - 让程序生成 core 文件,然后启动您的 debugger 看看核心。
    • 不看它是如何调用的,就无法确切知道故障是如何发生的。
    • int main() { StudentNode student = { 11111, "Afonso Henriques", 1, NULL }; StudentNode * 部分[3] = { NULL, NULL, NULL }; buildStudentSections(sections, &student, 1);返回0; }
    【解决方案2】:

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

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

    【讨论】:

    • 现在我收到错误第 7 行:1961 Segmentation fault 为什么?
    【解决方案3】:

    改变这个:

    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); 
    
    
            }   
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2020-08-19
      • 2021-03-17
      • 1970-01-01
      相关资源
      最近更新 更多