size of c array of struct at runtime

Viewed 434

I need to make an array of structs. It's not until I run the program that I'll know how many structs I'll need to store in the array. The plan was to pass a pointer to a struct to an function that'll read data into it but I'm making som stupid mistake. Here's some code to illustrate what I'm trying to do:

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

typedef struct {
    int myVar;
} myStruct;

myStruct *myBigList = NULL; 

int defineMyList(myStruct **myArray) {  
    int i = 0, size = rand() % 10;
    *myArray = malloc(size * sizeof *myArray);

    for (i = 0; i < size; i++) {
        myStruct *aStruct = malloc(sizeof(myStruct));
        aStruct->myVar = i + 1;
        myArray[i] = aStruct;
    }
    return size;
}

int main() {
    int size = 0, i = 0;
    srand(time(NULL));

    size = defineMyList(&myBigList);

    for (i = 0; i < size; i++)
        printf("myBigList[%i].myVar: %i\n", i, myBigList[i].myVar);

    return EXIT_SUCCESS;
}

I adapted this code from another question that had a problem similar to mine.

My problem is that when I try to print out the array in main after I put data into it I just get this:

myBigList[0].myVar: 1
myBigList[1].myVar: 0
myBigList[2].myVar: 0
myBigList[3].myVar: 0
myBigList[4].myVar: 0

When I was expecting this:

myBigList[0].myVar: 1
myBigList[1].myVar: 2
myBigList[2].myVar: 3
myBigList[3].myVar: 4
myBigList[4].myVar: 5

I suspect I've misunderstood something with indexing and pointers. When I run the program with valgrind it reports "Invalid read of size 4 at 0x40074D: main" and "Address 0x51fc0d4 is 0 bytes after a block of size 4 alloc'd at 0x4C2AB80: malloc".

3 Answers
Related