gpt4 book ai didi

c - 使用指针在结构中输入

转载 作者:行者123 更新时间:2023-11-30 18:41:35 24 4
gpt4 key购买 nike

我正在尝试从用户那里获取一些输入到此函数中的结构:

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')

关于c - 使用指针在结构中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20825625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com