First things first: don't cast the pointer malloc
returns. void*
to (in your case) double*
is implicit (and expected), casting it explicitly is generally considered bad practice.
Now on to your problem; malloc
allocates the given number of bytes and returns a pointer to those bytes. You allocate 1000 bytes, but what you want is to allocate enough bytes for 1000 double
s. The reason for your error is that a double
is larger than a single byte - it's 8 bytes. You can get the size of a type with sizeof(type)
; to allocate enough memory for your 1000 double
s, you'd therefore have to change the line inside the loop to:
myDoubles[i] = malloc(1000 * sizeof(double));
To get to know the size of the type on your system, you can put
printf("Size of double: %d", sizeof(double));
In your code.
Edit:
Now, since you're working with C++, you should not be using malloc
at all. C++ makes life easier and gives you new
!
The allocating line should be
myDoubles[i] = new double[1000];
The nice thing abour new is that it does not need the size supplied... you give it a type and an amount; it computes the bytes needed for you. But beware, instead of free
you should use
delete[] myDoubles[i];