【发布时间】:2019-04-01 05:11:48
【问题描述】:
当我尝试将scanf 数字添加到结构时,我得到了一些Segmentation fault。
我不知道scanf 是否与这种情况下的故障有关。
我认为我分配的内存很好,我在过去 2 小时内阅读了有关此故障的信息,并且在任何地方阅读了有关内存分配问题的信息,但在我的代码中没有看到这一点。
我的代码:
#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(¤t);
readEmail(¤t);
readPhone(¤t); // I got the error here, but only if I try this with numbers, with letters save only 0
readSize(¤t);
current.systime = time(NULL);
// ** //
checkValues(¤t);
return 0;
}
【问题讨论】:
-
在您的
readPhone函数中,您是要读取字符串还是整数?对于读取整数,您需要传递给scanf的参数是什么? -
请启用警告;他们可以帮助您解决
scanf格式不匹配的问题。每当您使用%s或%[扫描字符串以外的内容时,您必须传递存储结果的变量的地址。所以它是scanf("%i", &current->size)等等。 -
@Someprogrammerdude 我想保存电话号码,所以最多 15 个号码长度整数
-
@MOehm 是的,这对我有帮助,请写下它作为答案,然后我可以接受它
-
一般来说,对于要计算的数字,例如年龄、价格或数量,最好使用数字类型(例如 int)。真正作为标签的数字——例如电话号码或街道号码——最好保存为字符串。这样,您就可以捕捉到准确的表示,而不会丢失任何内容。
标签: c struct segmentation-fault scanf