-5

I've been trying to solve the "MIME type" puzzle from this site: https://www.codingame.com/games/puzzles/

And I've found an answer to this puzzle on the following site: http://ethiery.vvv.enseirb-matmeca.fr/CGsolo/mime-type.html

  1. Can somebody explain what the p = d.elmts+i; (line 49) from the above link does?
  2. Why doesn't it work when I omit the 49th line and use this code in the subsequent lines instead? (It does not show an error till I try to print the ext and mimes using the d.elmts[i].ext/mime). It works like a charm when I use the p = d.elmts+i;. (First time on stackoverflow. I'm not sure if this'll appear as a code snippet. Apologies if it doesn't)

Code

d.elmts[i].ext = malloc(11*sizeof(char));
d.elmts[i].mime = malloc(51*sizeof(char));
scanf("%s %s\n",d.elmts[i].ext, d.elmts[i].mime);
LPs
  • 16,045
  • 8
  • 30
  • 61
B Sumanth
  • 35
  • 1
  • 1
  • 6

2 Answers2

0

elmts is of datatype pair.

p = d.elmts+i;

This expression just assigns the next pair to p based on i. The pointer will be moved to the sizeof(pair) * i from elmts(Pointer arithmetic).

The pair contains the following 2 pointer members and you need to allocate memory before using them. That is what the next 2 lines do.

char *ext; char *mime;

If the pointer is not moved it will be pointing to the same pair.

The equivalent array expression for "p = d.elmts+i" is

p = &(d.elmts[i]);
Umamahesh P
  • 1,224
  • 10
  • 14
0
  1. p is a pointer to a structure - this means that p 'holds' the starting address for a structure in memory -- Hence: p = d.elmts+i represents the starting address in memory, for the current structure (i represents the address offset). In this example memory has been allocated for 'dictSize' structures (i.e. the number of structures). Note that the memory for the structures is allocated contiguously (i.e.next to each other) and can therefore be easily accessed using the start address of the reserved memory (i.e. d.elemts) and some offset i.e. i

  2. If a pointer to a a structure is declared then the underlying structure members can only can be accessed by the pointer when the arrow notation is used. If a structure is declared (not a pointer to a structure) then the underlying structure members can be accessed using the dot notation.

  3. using the '[]' notation in C - may be interpreted as trying to assigning an actual value (to memory that has been allocated) - whereas the pointer notation used in lines 50 and 51 is just enabling the allocating memory i.e. points to the start address of the memory being allocated - to hold possible values that each of the members may assume i.e. have not put values in this memory just yet - have to create/allocate memory first.

Grant Shannon
  • 4,709
  • 1
  • 46
  • 36