0

Here the printAdd function is not working and I am not sure why. There is no error shown in the terminal it just doesn't print the info.

#include<stdio.h>

struct address {
    int houseNo;
    int block;
    char city[100];
    char state;
};

void printAdd(struct address add);

int main(){
    struct address add[5];
    printf("enter info for person 1 : \n");
    scanf("%d", &add[0].houseNo);
    scanf("%d", &add[0].block);
    scanf("%s", &add[0].city);
    scanf("%s", &add[0].state);


    printAdd(add[0]);

    
    return 0;
}

void printAdd(struct address add){
    printf("address is : %d, %d, %s, %s\n", add.houseNo, add.block, add.city, add.state);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • It is printing it. Your app is exiting before it can be seen. Add code to wait for a keypress before you return. – Ken White Oct 16 '22 at 18:13
  • the posted code does not cleanly compile! always enable the warnings options when compiling for `gcc` suggest using the options: `-Wall -Wextra -Wconversion -pedantic -std=gnu11` – user3629249 Oct 17 '22 at 19:46

2 Answers2

1

These calls of scanf

scanf("%s", &add[0].city);
scanf("%s", &add[0].state);

are incorrect.

You should write

scanf("%99s", add[0].city);
scanf(" %c", &add[0].state);

Pay attention to the leading space in the format string in the last call of scanf. It allows to skip white space characters.

Also in the call of printf you have to write

printf("address is : %d, %d, %s, %c\n", add.houseNo, add.block, add.city, add.state);

That is the last conversion specifier shall be %c instead of %s.

And it will be better to declare the function like

void printAdd( const struct address *add);

That is instead of passing the whole structure it will be better to pass a pointer to the object of the structure type.

void printAdd( const struct address *add){
    printf("address is : %d, %d, %s, %c\n", add->houseNo, add->block, add->city, add->state);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Very likely this is the problem:

scanf("%s", &add[0].state);

Here you ask scanf to read a string into the single-character state member. Either read a character with %c or make state an array that can hold at least two characters (for a single-character "state" designation).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621