[英]Using pointers to input in a struct
我试图在此功能中从用户获取一些输入到结构:
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()时发生运行时错误,因此我认为我在处理指针的方式上做错了。
编译所有警告和调试信息(例如gcc -Wall -g
)。 学习使用调试器(例如gdb
)。
然后,您应该使用scanf(3)的结果。 它给出了真正阅读项目的数量。
而while((scanf("%c", inp)) != ("A"||"B"))
是非常错误的。 我确定编译器会警告您!
应该
char inp = 0;
while (((inp=0),scanf(" %c", inp) == 1) && inp != 'A' && inp != 'B')
首先scanf应该给出运行时错误。 scanf期望一个变量的位置,将从用户读取的值放在该变量中。
而不是scanf("%d", (x->any));
您应该写scanf("%d", &(x->any));
因为当您通过malloc分配内存时,所有字节都将被赋值为0。
所以基本上是通过写scanf("%d", (x->any));
您是说从用户读取到存储位置0的put值。这是错误的。
当您调用add()函数时,我在您的代码中发现了另一个错误。
它希望将Item *
作为第二个参数。 而当您通过add(A, *x);
调用它时add(A, *x);
并add(B, *x);
您传递的是Item
而不是Item *
。 bcz x本身是Item *
类型变量。 所以应该这样称呼它add(A, x);
。
干杯:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.