c-分段故障与结构之间的关系



当我尝试将scanf数字传递到结构时,得到了一些Segmentation fault。我不知道scanf和这种情况下的故障之间是否有关系。我认为我分配的内存很好,我在过去的两个小时里读到了关于这个错误的文章,我读到的所有地方都有关于内存分配问题的文章,但我在代码中没有看到这一点。我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#define MAX_STRING_LEN 80
#define PHONE_NUMBER 15
struct order {
time_t   systime;
char     name[MAX_STRING_LEN];
char     email[MAX_STRING_LEN];
int      phonenumber;
int      size;    
};

//functions
void readName(struct order *current);
void checkValues(struct order *current);
void readEmail(struct order *current);
void readPhone(struct order *current);
void readSize(struct order *current);
//read name
void readName(struct order *current){
printf("name: ");
scanf("%80[^n]", current->name);
// scanf("%s",current->name);
}
//read email
void readEmail(struct order *current){
printf("e-mail: ");
char tmp[80];
scanf("%s[^n]",current->email);
}
//read phone number
void readPhone(struct order *current){
printf("phone: ");
scanf("%15i[^n]", current->phonenumber);
}
//read size of order
void readSize(struct order *current){
printf("size: ");
scanf("%i", current->size);
}
void checkValues(struct order *current){
printf("Name: %s n",current->name);
printf("e-mail: %s n", current->email);
printf("tel: %d n", current->phonenumber);
printf("size: %d n", current->size);
printf("time: %ld n", current->systime);
}
//***
int main(k)
{
struct order current; //struct init
//read values
readName(&current);
readEmail(&current); 
readPhone(&current); // I got the error here, but only if I try this with numbers, with letters save only 0
readSize(&current);
current.systime = time(NULL);
// ** //
checkValues(&current);
return 0;
}

scanf("%15i[^n]", current->phonenumber);

正如已经指出的,这应该是:

scanf("%15i", &current->phonenumber);

(你在readSize中也重复了同样的错误。(

通常,编译时应使用编译器最多可使用的警告。一个好的编译器会警告您,当需要指针时,您正在将int传递给scanf

我想保存电话号码,所以最多15个数字长度整数

在一个典型的系统上,sizeof(current->phonenumber) == 4。这意味着您可以存储在该变量中的最高值是INT_MAX == 2147483647。这只是10位数字,并不是每个10位数字都适合。

如果您希望能够存储每一个可能的15位数字,则需要以不同的方式存储它们(在char phone[16]int64_t中(。

最新更新