Search code examples
carrayspointersstructallocation

Struct pointed by an array? [C]


I'm trying to make a program that uses a structure pointed by an array of 30. Which means, there will be only 30 available structures named Person. Think of this as an Activity line, the Activity line can only have 30 active Persons. Functions used are:

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

struct Person
{
    char name[40];
    char firstname[40];
    int CIN[12];
};

typedef struct Person *Activity;

main()
{
    Activity act[30];
    return 0;
}

Vacant(searches if there is an empty place in the Activity line).

insertion(Inserts new Persons IF a place is empty in the Activity line).

withdrawal(Removes a Person from the Activity line).

This is the declaration of the structure and the Activity line:

CIN is French for National Card Identity.

The functions are:

vacant(Activity act, int index);
insertion(Activity act, int index);
withdrawal(Activity act);

index is the number of the empty place, must be used in insertion.

My questions are:

  1. Is the declaration I made correct?
  2. If; considering the declaration is correct, the size of the array is 30 and the array points to the structure, does it mean I don't need to allocate the memory dynamically?(Using malloc function).
  3. Considering I'm on the right path. Does accesing field "name" for example go like this: "act.name"?

Solution

    1. In the declaration I cannot find anything terribly wrong

    2. Since it is an array of pointers to structs and not an array of structs, you just have to use malloc when you create a Person and then assign the returned pointer to one position of the array. But you do not need to use malloc at any other time with the code shown.

    3. No, the dot is to access a field of an struct, for example if you have Person peter it would be peter.name. To access the struct from the array it should be (*act[i]).name or act[i]->name.

    Hope this helps you; I am learning as you so maybe a more experienced user can help you more.