【发布时间】:2014-01-16 12:24:55
【问题描述】:
我试图从用户那里得到一些输入到这个函数中的结构:
void adding(){
Item *x = malloc(sizeof(Item));
printf("Enter an integer.");
scanf("%d", (x->any));
printf("Enter a string.");
scanf("%s", (x->text));
printf("Which set would you like to add the Item to A/B?");
while((scanf("%c", inp)) != ("A"||"B")){
printf("Set does not exist\n");
}
if(A == inp)
add(A, *x);
else
add(B, *x);
}
Item结构如下:
typedef struct anything{
char text[MAXI];
int any;
}Item;
最后调用的add函数就是这个:
void add(Array *S,Item *x){
bool rep = false;
int i = 0;
for(i = 0; i<(S->size); i++){
if(compStructs(x,S->arr+i))
rep = true;
}
if(rep == false){
Item *p2 = realloc(S->arr, (S->size+1)*sizeof(Item));
*p2 = *x;
(S->size)++;
}
else
printf("The item is already in the set.");
}
由于遇到第一个 scanf() 时发生运行时错误,我认为我在处理指针的方式上做错了。
【问题讨论】:
-
开启编译器警告。还要考虑
scanf()如何修改它的参数。此外,不要使用scanf(),这是错误的和邪恶的。使用fgets()或fgetc()获取用户输入,使用strtol()、strtod()、strtok_r()、strchr()和strstr()进行解析。