[英]return value 3221225477 after the program finishes
我正在學習如何在C中進行編碼。我必須為一個人創建一條記錄,其中包含一個生日和一個ID號,該代碼由3個文件組成
拳頭是頭
// definição do tipo
typedef int vetor[10];
typedef struct
{
char nome[50];
vetor nasceu;
vetor cpf;
} dados ;
void cadastro (dados*, char[50], vetor, vetor);
然后是標題的定義
#include <stdio.h>
#include <string.h>
#include "cadastro.h"
void cadastro (dados *usuario, char name[50], vetor ddn, vetor cpf)
{
int i;
strcpy(usuario->nome,name);
for (i = 0; i < 50; i++)
{
usuario->nasceu[i] = ddn[i];
}
for (i = 0; i < 10; i++)
{
usuario->cpf[i] = cpf[i];
}
}
最后一個文件使用標題生成記錄
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cadastro.h"
int preenche_cadastro (char a[],vetor b,vetor c)
{
int i;
printf ("inserir nome: ");
gets (a);
printf("inserir data de nascimento (campos separados por espaco): ");
for (i = 0; i < 3; i++)
{
scanf("%d",&b[i]);
}
printf ("inserir CPF (campos separados por espaco): ");
for (i = 0; i < 4; i++)
{
scanf("%d",&c[i]);
}
return (0);
}
int imprime_cadastro (dados usuario)
{
printf("\nnome: %s",usuario.nome);
printf("\ndata de nascimento: %d / %d / %d\n", usuario.nasceu[0],usuario.nasceu[1],usuario.nasceu[2]);
printf("CPF: %d . %d . %d - %d\n", usuario.cpf[0],usuario.cpf[1],usuario.cpf[2],usuario.cpf[3]);
return(0);
}
int main(void)
{
dados new_entry;
char name[50];
vetor born, cpf;
int i;
preenche_cadastro (name,born,cpf);
cadastro(&new_entry, name, born, cpf);
imprime_cadastro(new_entry);
return (0);
}
我真的不知道如何調試,但據我所知,“分段故障”僅在生產線上發生
return (0);
我要瘋了,有人可以幫我嗎?
對不起,我的英語不是母語
您的第一個循環應僅復制10個項目,而不是50個項目。
for (i = 0; i < 10; i++)
{
usuario->nasceu[i] = ddn[i];
}
您通過訪問該行中超出數組的范圍來調用未定義的行為
usuario->nasceu[i] = ddn[i];
在cadastro
函數中,然后程序恰巧在那里崩潰了。
不要調用未定義的行為 。 您應該定義數組中的元素數量並使用它,而不是使用幻數10
。
還要注意,使用不確定的具有自動存儲持續時間的變量的值(不確定的)也會調用未定義的行為 。
更正的標題:
// definição do tipo
#define VETOR_NUM 10
typedef int vetor[VETOR_NUM];
typedef struct
{
char nome[50];
vetor nasceu;
vetor cpf;
} dados ;
void cadastro (dados*, char[50], vetor, vetor);
更正了cadastro
實現:
#include <stdio.h>
#include <string.h>
#include "cadastro.h"
void cadastro (dados *usuario, char name[50], vetor ddn, vetor cpf)
{
int i;
strcpy(usuario->nome,name);
for (i = 0; i < VETOR_NUM; i++)
{
usuario->nasceu[i] = ddn[i];
}
for (i = 0; i < VETOR_NUM; i++)
{
usuario->cpf[i] = cpf[i];
}
}
更正的main()
函數:
int main(void)
{
dados new_entry;
char name[50];
vetor born = {0}, cpf = {0}; /* initialize arrays */
/* i is removed because it wasn't used */
preenche_cadastro (name,born,cpf);
cadastro(&new_entry, name, born, cpf);
imprime_cadastro(new_entry);
return (0);
}
還有一點需要注意:您不應該使用gets()
,因為它不可避免地存在緩沖區溢出的風險。
cadastro
函數中的以下循環:
for (i = 0; i < 50; i++)
{
usuario->nasceu[i] = ddn[i];
}
似乎與nasceu
的大小nasceu
:
typedef int vetor[10];
typedef struct
{
char nome[50];
vetor nasceu;
vetor cpf;
} dados ;
您是否嘗試過更改為:
for (i = 0; i < 10; i++)
{
usuario->nasceu[i] = ddn[i];
}
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.