0

Below code works (no errors) but I get strange output such as this from the code below:

OUTPUT:

Name is 8îk and quantity is 0

Name is ░îk and quantity is 2130567168

Where is my mistake?

#include <stdio.h>
#include <stdlib.h>

void display(struct item *);

struct item{

char name[50];
int quantity;

};

int main(void){

struct item *first = (struct item *)malloc(sizeof(struct item));
strcpy(first->name, "Banana");
first->quantity = 32;

struct item *second = (struct item *)malloc(sizeof(struct item));
strcpy(second->name, "Apple");
second->quantity = 432;

display(&first);
display(&second);

getch();

}

 void display(struct item *i){

printf("Name is %10s and quantity is %7d\n", i->name, i->quantity);

}
Lyrk
  • 1,936
  • 4
  • 26
  • 48

4 Answers4

3

The first and seconds are already pointers, so you don't need to pass their address, but their value (address of the struct they're pointing at):

display(first);
display(second);
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
1
display(first);
display(second);

first and second are already pointers, as required by display structure.

Alex F
  • 42,307
  • 41
  • 144
  • 212
1

As well as the obvious errors when calling display(), you are also missing #include <string.h>. If you had compiled with warnings enabled you would have been alerted to this, and to the problem with the calls to display(), and several other problems too:

Line 4: warning: 'struct item' declared inside parameter list
Line 4: warning: its scope is only this definition or declaration, which is probably not what you want
In function 'main':
Line 16: warning: incompatible implicit declaration of built-in function 'strcpy'
Line 23: warning: passing argument 1 of 'display' from incompatible pointer type
Line 24: warning: passing argument 1 of 'display' from incompatible pointer type
t.c: At top level:
Line 30: error: conflicting types for 'display'
Line 4: error: previous declaration of 'display' was here

The moral of the story: always compile with warnings enabled, and take heed of any warnings!

One further point to note: you should never cast the result of malloc in C, e.g.

struct item *first = malloc(sizeof(struct item)); // do not apply redundant and
                                                  // potentially dangerous cast!
Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
1

You're passing the address of the pointer to a struct to the function "display" rather than passing the address of the struct itself. (you're passing "struct item **").

display(first); display(second); will solve the problem.

Chantara
  • 13
  • 2