title: Modifying individual elements of an array of structures through a function
body: <p>I have this piece of code which is supposed to record city names and their total cases of covid in an array of structure. Memory allocation has to be done dynamically and initially there are 3 empty spaces. After user inputs 3 cities, more memory is allocated for the next addition. However, whenever I add a city and total number of cases, I cannot access them. I get random directories, characters, or random numbers. I think there is a problem with the way I use pointers. What exactly am I doing wrong?</p>
  <pre><code>    #include &lt;stdio.h&gt;
      #include &lt;stdlib.h&gt;
      #define  MAX_CHAR 50
      
      typedef struct covid_cities{
          char name[MAX_CHAR];
          int cases;
          int ID;
      }COVID;
  
  void addCity(COVID *cities, int number_of_cities){
      if (number_of_cities&lt;3){
          cities[number_of_cities].ID=number_of_cities;
          printf(&quot;Enter the name of the city: &quot;);
          scanf(&quot;%s&quot;, cities[number_of_cities].name);
          printf(&quot;Enter the total covid cases: &quot;);
          scanf(&quot;%d&quot;, &amp;cities[number_of_cities].cases);
          printf(&quot;%s is added!\n&quot;, cities[number_of_cities].name);
      }
  
      else{
          cities = (COVID *)realloc(cities, (number_of_cities+2)*sizeof(COVID));
          cities[number_of_cities].ID=number_of_cities;
          printf(&quot;Enter the name of the city: &quot;);
          scanf(&quot;%s&quot;, cities[number_of_cities].name);
          printf(&quot;Enter the total covid cases: &quot;);
          scanf(&quot;%d&quot;, &amp;cities[number_of_cities].cases);
          printf(&quot;%s is added!\n&quot;, cities[number_of_cities].name);
      }
  }
  int main(void){
      int number_of_cities = 0;
      while(1){
          int user_input;
          COVID *cities;
          cities = (COVID *)malloc(sizeof(COVID)*3);
          printf(&quot;Covid Cases By City\n&quot;);
          printf(&quot;1) Add city\n&quot;);
          printf(&quot;What would you like to do? &quot;);
          scanf(&quot;%d&quot;, &amp;user_input);
          switch(user_input){
              case 1:
                  addCity(cities, number_of_cities);
                  number_of_cities++;
                  break;
             default:
                  printf(&quot;Invalid Input\n&quot;);
          }
      }
  }
  </code></pre>