简体   繁体   中英

Using pointers to input in a struct

I am trying to get some input from the user to a struct in this function:

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

}

The Item struct is as follows:

typedef struct anything{
    char text[MAXI];
    int any;
}Item;

The add function which is being called in the end is this one:

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.");

}

Since a runtime error is occuring when the first scanf() is encountered, I think that I'm doing something wrong in the way I'm handling pointers.

Compile with all warnings and debugging info (eg gcc -Wall -g ). Learn to use a debugger (eg gdb ).

Then, you should use the result of scanf(3) . It gives the number of really read items.

And while((scanf("%c", inp)) != ("A"||"B")) is very wrong. I'm sure the compiler would have warned you!

Should be

char inp = 0;
while (((inp=0),scanf(" %c", inp) == 1) && inp !=  'A' && inp != 'B')

first scanf should give a runtime error. scanf expects a location of a variable in which the value read from user would be put.

instead of scanf("%d", (x->any)); you are supposed to write scanf("%d", &(x->any));

because when you allocate memory via malloc all the bytes would be assigned value = 0.

so basically by writing scanf("%d", (x->any)); you are saying put value read from user to memory location 0. which is error.

there is one more error which i have found in your code is when you are calling add() function.

it expects Item * as a second argument. while when you are calling it by add(A, *x); and add(B, *x); you are passing Item and not Item * . bcz x itself is a Item * type variable. so you are supposed to call it like this add(A, x); .

Cheers:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM