【发布时间】:2014-01-23 16:36:45
【问题描述】:
我有一个指向结构的指针。
typedef struct anything{
char text[MAXI];
int any;
}Item;
在接收到结构体中的输入后,程序会请求用户将结构体存储在哪个集合中。
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?");
char inp1 = 0;
while ((inp1=0),scanf("%s", &inp1) == 1 && (inp1 != 'A') && (inp1 != 'B')){
printf("Set does not exist\n");
}
if('A' == inp1)
add(A, x);
else
add(B, x);
flush();
instructs();
}
当接收到输入时(在 while 循环中),指针 x 正在从 0x570ff8 修改为 0x57f00,然后它将指向垃圾而不是下面请求的输入。
为什么要更改指针?
谢谢。
添加函数:
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){
x = realloc(S->arr, (S->size+1)*sizeof(Item));
(S->size)++;
printf("Item has been added");
}
else
printf("The item is already in the set.");
}
【问题讨论】:
-
(inp1=0)那么什么时候(inp1=0)会是'A'?或者这个修改不是一个单一的序列? -
显示
add()的代码。 -
inp1 用于确保 scanf 读取 1 个项目。 inp1!= A 和 inp!= B 也用于在输入无效输入时通知用户。