我用 C 创建了一个包含 3 个文件的项目,main.c,我在其中编写了 main:
main.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/