0

I'm new to C. Below are codes written in C.

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

typedef struct {
    char name[256];
    int age;
    int sex;
} People;

void InputPeople(People *data);
void ShowPeople(People data);

int main(void)
{
    int i,count,datasize;
    People *data;

    datasize = 10;
    data = (People*)malloc(sizeof(People) * datasize);

    count = 0;
    while (1) {
        InputPeople(&data[count]);
        if (data[count].age == -1) break;
        count++;

        if (count >= datasize) {
            datasize += 10;
            data = (People*)realloc(data,sizeof(People) * datasize);
        }
    }

    for (i = 0;i < count;i++) {
        ShowPeople(data[i]);
    }

    free(data);

    return 0;
}

I have no idea why it is possible to write like "data[count]". I've learned Structure and Array. I would appreciate if somebody could explain to me.

  • 2
    In many ways pointers and arrays are treated as the same thing. One example being that you can use array-indexing for both. – Some programmer dude Jun 06 '17 at 12:46
  • 4
    Also, it seems you really should [find a good beginners book about C to read](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list), instead of asking extremely basic questions. – Some programmer dude Jun 06 '17 at 12:48
  • 4
    Also you should think about what part of your code example is relevant to your question. – harper Jun 06 '17 at 12:50
  • Thank you so much for your advice. I'm currently learning in the internet. I will buy a good beginners book about C. – Naoyuki Nishimura Jun 06 '17 at 13:16

1 Answers1

2

People is your struct.

You declare a People pointer, which then points to the memory that you dynamically allocated with malloc(). How big is that memory chunk you allocated? datasize * size of the struct, i.e. 10 structs, since datasize = 10.

That means that data now points to a 1D array, thus you can index it like data[0] to get the first element (struct). count is a counter, which can be 0 as well.

You can think it like you had done People data[10];, which statically declares an array of 10 structs People, although it's not the same, since in your code the memory is dynamically allocated.


BTW, Do I cast the result of malloc? No.

Also, I would suggest you to read a C book.

gsamaras
  • 71,951
  • 46
  • 188
  • 305