c - 应用程序因指针、头文件和结构数组而崩溃

标签 c arrays eclipse pointers struct

我用 C 创建了一个包含 3 个文件的项目,main.c,我在其中编写了 main:

ma​​in.c

#include <stdlib.h>
#include <stdio.h>

typedef struct{
    char nome[29];
    char cognome[28];
    int et;
}s_persona;

int main(){
    s_persona personaX[5];

    caricamento(&personaX[5]);

    int i;

    for(i=0;i<=5;i++){
        printf("Nome: %s\t Cognome: %s\t Eta': %d\n", personaX[i].nome, personaX[i].cognome, personaX[i].et);
    }

    system("pause");
}

然后是一个带有原型(prototype)的头文件(struct.h):

#ifndef STRUCT_H_
#define STRUCT_H_

void caricamento(s_pers perso[5])

#endif /* STRUCT_H_ */

和另一个带有函数的源文件(struct.c):

#include <stdlib.h>
#include <stdio.h>

typedef struct{
    char nome[29];
    char cognome[28];
    int et;
}s_pers;

void caricamento(s_pers* perso[5]){
    int k;

    for(k=0;k<=5;k++){
        printf("Inserisci nome dello studente: ");
        scanf("%s", perso[k]->nome);

        printf("Inserisci cognome dello studente: ");
        scanf("%s", perso[k]->cognome);

        printf("Inserisci l'eta' dello studente: ");
        scanf("%d", &perso[k]->et);
    }
}

好的,我用过的文件都在这了。 Eclipse 构建项目,没有错误,但是,当我插入第一个字符串时,应用程序停止工作并崩溃。 我尝试创建另一个像这样的应用程序,但不使用结构数组,并且它工作正常...... 我如何解决这个问题?

谢谢!!

最佳答案

您的标题根本没有被使用。最好在 header 中定义结构并将 header 包含在源文件中(如上面的评论中所述)。

#ifndef STRUCT_H_
#define STRUCT_H_

typedef struct{
    char nome[29];
    char cognome[28];
    int et;
} s_pers;

void caricamento(s_pers *perso)

#endif /* STRUCT_H_ */

然后在你的 main.c include 中标题以及评论中也提到的通过 personaX 。否则,您将传递第六个元素的地址,该地址甚至不存在!由于数组从 0 开始,您只能迭代直到 k < 5 .

#include <stdlib.h>
#include <stdio.h>
#include <struct.h>    /* include your header! */

/* 
  Structure already defined in header, 
  no need to define it here! 
 */

int main(){
    s_pers personaX[5];

    caricamento(personaX);

    int i;
    for(i=0;i<5;i++){
        printf("Nome: %s\t Cognome: %s\t Eta': %d\n", 
            personaX[i].nome, personaX[i].cognome, personaX[i].et);
    }

    system("pause");
}

在你的 struct.c 中,确保包含你的头文件,并确保你的函数与头文件中的函数声明相匹配!再次确保停在 5,所以使用 k < 5 .

#include <stdlib.h>
#include <stdio.h>
#include <struct.h>    /* include your header! */

void caricamento(s_pers* perso){
    int k;

    for(k=0;k<5;k++){
        printf("Inserisci nome dello studente: ");
        scanf("%s", perso[k].nome);

        printf("Inserisci cognome dello studente: ");
        scanf("%s", perso[k].cognome);

        printf("Inserisci l'eta' dello studente: ");
        scanf("%d", &perso[k].et);
    }
}

关于c - 应用程序因指针、头文件和结构数组而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50131740/

相关文章:

C、malloc、free 和自动检查

c - 当 block 被 free() 从堆中释放时会发生什么?

c - 简单的 C 源代码中有错误吗?

php - mysql 更新的动态数组创建 - php

c - 执行recv()和send()winsock

c++ - 将数组中的所有 float 元素添加到另一个数组中的每个 float 的优化方法

sql - 在复合类型数组中搜索元素

java - 获取 Eclipse RCP 中的 Activity 插件列表

python - eclipse-python IDE if else 匹配行/指示器

java - Eclipse 类文件元数据