0

I'm currently creating an array of structs, and when i initialize the array, it is starting with 8 elements in the struct, instead of 1. Why is it doing this? If more code is needed (but i doubt it as they are all seperate functions, i can post it if asked) This is the relevant bits of code:

typedef struct {
        int valid;
        int row, col;
} Point;

typedef struct {
        Point point;
        int number;
        char name;
        char param[20];
        char type[20];
} Agent;





int main(int argc, char **argv)
{
        int steps;
        int listSize = 0;

        Agent *agentList = (Agent *) calloc(1, sizeof(Agent));
        printf("%d size of agentList when initialised\n", sizeof(agentList));
        if (argc != 4) {
                error(SHOW_USAGE);
        }

        sscanf(argv[2], "%d", &steps);
        if ((steps < 1)) {
                error(BAD_STEPS);
        }

        readMap(argv[1]);
        agentList = readAgentFile(argv[3], agentList);
        print_agents(agentList);
        return 0;

2 Answers 2

1
printf("%d size of agentList when initialised\n", sizeof(agentList));

This will give you the size of the agentList pointer which will most likely be four or eight in current systems.

Similarly, sizeof(*agentList) would simply give you the size of the structure pointed to by agentList but that's a single element of the array rather than the entire array.

There is no way to get from a pointer to the size of the array pointed at by it, simply because a pointer points at a single thing, not an array. By that, I mean it may well point to the first element of an array but that's not the same thing as pointing at an array. The distinction is subtle but important.

If you want to know the size of an array where the only thing you have is a pointer to it, you will have to remember it separately.

Sign up to request clarification or add additional context in comments.

Comments

1

This here is not giving you the size of the array, but giving you the size of the pointer:

printf("%d size of agentList when initialised\n", sizeof(agentList));

It's not possible to determine the size of the array from the pointer, you need to store the size of the array separately and carry it around with the array.

This is why you will notice many functions in C will have both a pointer and a size argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.