1

I am trying to make a malloc based on a struct.

The struct looks like this:

    struct shirts
        {
        char color[10];
        int size;
        };

struct shirts* ptr_shirts;

I then want to make x amount of t-shirts so i have a variable for that:

printf("How many T-shirts? ");
            scanf("%d",&amount);
            getchar();
            ptr_shirts = (struct shirts *)malloc(amount * sizeof(struct shirts));

I then want to fille the spaces but i dont know how to do it. I have tried to use a for loop and put in values like it is an array:

for(i = 0; i<amount;i++)
            {
            printf("Color on T-shirt nr %d: ",(i+1));
            scanf_s("%s", "what to type here" ,sizeof(ptr_shirts->color));
            printf("Size on T-shirt nr %d: ",(i+1));
            scanf("%d",&"what to type here");
            }

i have tried with

ptr_shirts[i].size
ptr_shirts->size[i]
(ptr_shirts.size 
and then ptr_shirts++)

but i dont know how to make it easy becuase i want to fill more then 1 t-shirt, thats the problem i got

Robin Andersson
  • 87
  • 2
  • 11
  • You can use the pointer using array-indexing syntax, so `ptr_shirts[i].size` is correct, for values of `i` in the range 0 <= i < amount. – Some programmer dude Dec 11 '14 at 12:02
  • Observe that you have to pass the pointer to the `size` member, so you have to dereference with the ampersand (`&`). But in case of the `color` member, the `char` array will decay to a pointer to the first cell on its own. – bitmask Dec 11 '14 at 12:07
  • 1
    Oh and by the way, [in C you should not cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Some programmer dude Dec 11 '14 at 12:27

2 Answers2

1

For color array member note that scanf_s function is non-standard (well, to be honest in except to C11 with (optional though) Annex B, but it's not well-adopted yet), you might use fgets() along with stdin as an "safer" alternative.

In case of size member it should be just:

&ptr_shirts[i].size

(that is: scanf("%d", &ptr_shirts[i].size);)

or alternatively:

&(ptr_shirts + i)->size

Couple of additional notes:

Community
  • 1
  • 1
Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
-1
Try This -
ptr_shirts = (struct shirts *)malloc(amount * sizeof(struct shirts));

for(i = 0; i<amount;i++)
        {
           memset (ptr_shirts[i],0,sizeof(struct shirts)); /*Assign structure variable to NULL*/
           printf("Color on T-shirt nr %d: ",(i+1));
           scanf_s("what to type here %s", ptr_shirts[i].color,_countof(ptr_shirts[i].color));
           printf("Size on T-shirt nr %d: ",(i+1));
           scanf_s("what to type here %d", ptr_shirts[i].size,_countof(ptr_shirts[i].size));
        }
Sam
  • 19
  • 2