printing an array of structs

12,125

Solution 1

void add(part **item, int *part_count)
{
  char temp[100];

  if (!(*item)){
   //printf("first alloc\n");
       *item = malloc(sizeof(part)*3);
  }
  else if (*part_count>= 3){
  //printf("realloc\n");
      *item = realloc(*item, sizeof(part) * (*part_count + 1));
  }

  item[0][*part_count].name = malloc(sizeof(char)*100); // max of 100 characters

  printf("Please enter item name: \n");
  fgets(temp, 100, stdin);     
  strcpy(item[0][*part_count].name, temp);      


  printf("Please enter item price: \n");
  fgets(temp, 100, stdin);
  sscanf(temp, "%f", &item[0][*part_count].price);      


  printf("Please enter item quantity: \n");
  fgets(temp, 100, stdin);
  sscanf(temp, "%d", &item[0][*part_count].quantity);   


  *part_count = *part_count+ 1;
}

This ended up doing it. Not sure if using a **struct was necessary but was the only method I could get working.

Solution 2

item, being an argument to add is local to that function. So when you modify it, that doesn't affect the variable that you passed in to it. In order to get the modified item pointer back, you need to pass a pointer to it (a pointer to a pointer):

void add(part **item, int *part_count)

Then use *item (or (*item)) everywhere you currently use item within add

Share:
12,125
Tristan Pearce
Author by

Tristan Pearce

Updated on June 04, 2022

Comments

  • Tristan Pearce
    Tristan Pearce almost 2 years
    void print(part *item, int part_count) {
        int i=0;
    
        for (i=0; i<part_count; i++) {
           printf("Item number: %d\n", i + 1);
           printf("Item name: %s\n", item[i].name);
           printf("Item price: $%f\n", item[i].price);
           printf("Item quantity: %d\n", item[i].quantity);
        }
    }
    

    i want to print an array of structs created with a different function. I have looked but have yet to find a different way to print them or what i am doing wrong in the print statements. My program compiles but crashes upon running.

    ok well it is good to know the problem is not within these statements. That was frustrating me. here is the add function.

    void add(part *item, int *part_count)
     {
          if (!item)
          {
             item = malloc(sizeof(part));
          }
    
          item = realloc(item, sizeof(part) * *part_count + 1);
    
          item[*part_count].name = malloc(sizeof(char)*64); // max of 64 characters
    
          printf("Please enter item name: ");
          scanf("%65s", item[*part_count].name);
    
          printf("Please enter item price: ");
          scanf("%f", &item[*part_count].price);
    
          printf("Please enter item quantity: ");
          scanf("%d", &item[*part_count].quantity);
    
          *part_count = *part_count+ 1;
     }