Size of struct array at runtime

I need to create an array of structures. This is not until I run the program, I will know how many structures I will need to store in the array. The plan was to pass a pointer to the structure of a function that will read data into it, but I am making a dubious mistake. Here is 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 the array basically after entering data into it, I just get the following:

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 that I 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".

+4
3

. :

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

  for(i = 0; i < size; i++) {
    (*myArray)[i].myVar = i + 1;
  }

  return size;
}

, :

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

  myStruct * new_array = malloc(size * sizeof *new_array);
  if ( !new_array ) {
      perror("couldn't allocate memory for new array");
      exit(EXIT_FAILURE);
  }

  for ( i = 0; i < size; ++i ) {
      new_array[i].myVar = i + 1;
  }   

  *myArray = new_array;
  return size;
}
+4

. myBigList . ( ), .

, ( , ), - . , myArray - , ,

myArray[i] = aStruct;

(*myArray)[i] = aStruct;

. , :

  for(i = 0; i < size; i++) {
    (*myArray)[i].myVar = i + 1;
  }

, , .

, malloc(), . , size. (*myArray)[0] **myArray; *myArray - , .

+2

,

*myArray = malloc(size * sizeof **myArray);

p = malloc(n * sizeof *p);

.. * sizeof. p *myArray, sizeof **myArray.

+1

All Articles