Dynamic memory allocation problem

Write a program in that file to obtain nutritional information about several foods from the user then display a table containing this information.

The number of foods to be displayed is determined by the value of a macro named LUNCH_QTY that you must define and the information about each food is kept in a structure of the following type (The data types and member names must not be modified):

Function main must, and in the order specified:
1. in one single statement:
a. define the struct Food data type shown above and in the same statement
b. declare automatic array lunches[LUNCH_QTY], and in the same statement
c. explicitly initialize only elements lunches[0] and lunches[1], initializing them to an apple and a salad, respectively. Assume that an apple weighs 4 ounces and contains 100 calories and a salad weighs 2 ounces and contains 80 calories.

2. loop through each of the non-explicitly-initialized elements of the array and do the following in order during each iteration:
a. prompt the user to enter the whitespace-separated name, weight, and calories of a food in that order on the same line; the food name must not contain whitespace;
b. store the food name into a temporary character buffer you’ve declared and store the weight and calories values directly into the corresponding members of the structure in the current lunches array element;
c. determine the exact amount of space necessary to represent the food name including its null terminator character;
d. dynamically allocate the exact amount of memory determined in the previous step and store the pointer to it in the name member of the structure in the current lunches array element. Do not use calloc or realloc. If dynamic allocation fails output an error message to stderr and terminate the program with an error code.
e. Copy the food name into the dynamically allocated memory using the memcpy function.

3. display a table of all foods in the array along with their weights and calorie content, aligning the left edges of all foods and the least significant digits of all weights and calories. There must be nothing between these entries except the spaces needed for alignment (no commas, dividing lines, etc.).

4. free all dynamically allocated memory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mem.h>

#define LUNCH_QTY 5

int main() {
    struct Food
    {
        char *name;
        int weight, calories;
    } lunches[LUNCH_QTY] = {{"apple", 4, 100}, {"salad", 2, 80}};
    struct Food *ptr;
    char TempChar[LUNCH_QTY];
    int ArrayCount, i;

    for (ArrayCount = 2; ArrayCount < LUNCH_QTY; ++ArrayCount)
    {
        printf("Enter the information about food: ");
        scanf("%s %d %d", &TempChar[ArrayCount], &lunches[ArrayCount].weight, 
        &lunches[ArrayCount].calories);
        lunches->name = (char *) (struct Food *) malloc(LUNCH_QTY * 
        sizeof(TempChar));
        lunches[ArrayCount].name = &TempChar[ArrayCount];
        //memcpy (lunches[ArrayCount].name, &TempChar[ArrayCount], 
        sizeof(TempChar[ArrayCount]));
    }
    printf("Displaying Information:\n");
    for (i = 0; i < LUNCH_QTY; ++i)
    {
    printf("%s%10d%20d\n", lunches[i].name,lunches[i].weight, 
    lunches[i].calories);
    }
    return 0;
}
What's the problem in the code? Can anyone fix this. Thanks! Regards
What's the problem in the code?

That is a good question that you really should answer. What exactly is the program doing/not doing that you believe to be incorrect?

That is a good question that you really should answer. What exactly is the program doing/not doing that you believe to be incorrect?

Because I am getting some garbage values when I print the lunches[i].name at the end of code. I am not getting string that I entered via console. I am getting correct values of lunches[i].weight, lunches[i].calories as I am assigning directly from scanf.

Thanks!
I am getting this type of weird output.

Enter the information about food:Kiwi 2 56
Enter the information about food:Banana 9 78
Enter the information about food:Lemon 5 95
Displaying Information:
└$╕ 0 100
salad 2 80
KBL°[╕ 2 56
BL°[╕ 9 78
L°[╕ 5 95

Process finished with exit code 0
A good place to start is with your requirements pasted into the code as comments.

This level of micro-management specification is the coding equivalent of "painting by numbers".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define LUNCH_QTY 5

int main() {
  // Function main must, and in the order specified:
  // 1. in one single statement:
  // a. define the struct Food data type shown above and in the same statement
  // b. declare automatic array lunches[LUNCH_QTY], and in the same statement
  // c. explicitly initialize only elements lunches[0] and lunches[1],
  // initializing them to an apple and a salad, respectively.
  // Assume that an apple weighs 4 ounces and contains 100 calories
  // and a salad weighs 2 ounces and contains 80 calories.
  struct Food
  {
      char *name;
      int weight, calories;
  } lunches[LUNCH_QTY] = {{"apple", 4, 100}, {"salad", 2, 80}};

  int ArrayCount, i;

  // 2. loop through each of the non-explicitly-initialized elements of the array
  // and do the following in order during each iteration:
  for (ArrayCount = 2; ArrayCount < LUNCH_QTY; ++ArrayCount)
  {
    // a. prompt the user to enter the whitespace-separated name, weight, and calories of a food
    // in that order on the same line; the food name must not contain whitespace;
    printf("Enter the information about food: ");

    // b. store the food name into a temporary character buffer you’ve declared and
    // store the weight and calories values directly into the corresponding members
    // of the structure in the current lunches array element;
    char TempChar[100];
    scanf("%s %d %d", TempChar, &lunches[ArrayCount].weight, &lunches[ArrayCount].calories);

    // c. determine the exact amount of space necessary to represent the food name
    // including its null terminator character;
    size_t len = strlen(TempChar)+1;

    // d. dynamically allocate the exact amount of memory determined in the previous step and
    // store the pointer to it in the name member of the structure in the current lunches array element.
    // Do not use calloc or realloc. 
    lunches[ArrayCount].name = malloc(len);

    // If dynamic allocation fails output an error message
    // to stderr and terminate the program with an error code.

    // e. Copy the food name into the dynamically allocated memory using the memcpy function.
  }

  // 3. display a table of all foods in the array along with their weights and calorie content,
  // aligning the left edges of all foods and the least significant digits of all weights and calories.
  // There must be nothing between these entries except the spaces needed for alignment (no commas, dividing lines, etc.).
  printf("Displaying Information:\n");
  for (i = 0; i < LUNCH_QTY; ++i)
  {
    printf("%s%10d%20d\n", lunches[i].name,lunches[i].weight,
    lunches[i].calories);
  }

  // 4. free all dynamically allocated memory.
  return 0;
}


Apart from the mis-handling of the char array for the food name, it seems pretty much there.

I left a few steps for you :)

Topic archived. No new replies allowed.