user3266210
user3266210

Reputation: 299

how to printf a int struct member

My program asks client to input name and each time the int num increases by 1. My problem is when i printf the info the int num shows thousands! I think it shows the address.

typedef struct myphonebook {
    int num;
    char name[31];
    char address[101];
    char cellphone[11];
    char email[21];
} Myphonebooktype;

Myphonebooktype *pb = NULL;

for(i = addcounter, cc = addcounter + 1; i < 21; i++, cc++) {

    pb = (Myphonebooktype*)realloc(pb,cc*sizeof(Myphonebooktype));

    pb[0].num = 1;

    printf("Add a contact\n");

    printf("Contact no. %d\nEnter name);
    gets(pb[i].name);
    pb[i].num++;            
}

this is my print function

printf("Contact no %d\nName:%s", pb[i].num, pb[i].name);

I initialize the pb[0].num the first one only to one, and auto add using pb[i].num++, and then print, but when i print it shows me not 1 or 2 but 7thousand something plus.

Upvotes: 0

Views: 2628

Answers (2)

Marco A.
Marco A.

Reputation: 43662

I'll leave the other issues away and focus on your main one..

There's no "string" output in your code, "%d" means "output an integer" but I don't see any "%s" which means "output a string"

This is correct

printf("Contact no %d\nName: %s", pb[i].num, pb[i].name);

Even if fixed, I don't think anything's going to work: you're not initializing pb[i].num

Upvotes: 1

Roger Rowland
Roger Rowland

Reputation: 26279

You're missing the string token in the format string. Try this:

printf("Contact no %d\nName: %s", pb[i].num, pb[i].name);

Also, as @Oli Charlesworth commented, you don't initilaise all of the pb[].num variables, only the first one. So replace this

pb[0].num = 1;

With this

pb[i].num = i;

Upvotes: 4

Related Questions