Faulty use of constructor of dynamic array

Hello everyone,

According to someone, one can initialize a dynamically created array in the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
unsigned int * vec;
// ... do something to vec
double * a = (double *) malloc(4*sizeof(double));
a = (double[3]){	(double[3]){0.0,10.0,20.0}[vec[0]],
					(double[3]){1.0,2.0,3.0}[vec[1]],
					(double[6]){-2.0,-1.0,0.0,1.0,2.0,3.0}[vec[2]]
					}; // NO C COMPILER ERROR
					
double 	b[3];
b = (double[3]){	(double[3]){0.0,10.0,20.0}[vec[0]],
					(double[3]){1.0,2.0,3.0}[vec[1]],
					(double[6]){-2.0,-1.0,0.0,1.0,2.0,3.0}[vec[2]]
					}; // C COMPILER GIVES ERROR	



While there is no compilation error for the first assignment, the memory a is pointing to seems to change, surprisingly to me. This seems to solve the problem though:
1
2
3
4
5
memcpy(a, (double[3]){	(double[3]){0.0,10.0,20.0}[vec[0]],
					(double[3]){1.0,2.0,3.0}[vec[1]],
					(double[6]){-2.0,-1.0,0.0,1.0,2.0,3.0}[vec[2]]
					},
                                        3*sizeof(double)); // NO C COMPILER ERROR 




What does the first assignment do and why does it cause memory to change later in the program?
Last edited on
What does the first assignment do and why does it cause memory to change later in the program?


double * a = (double *) malloc(4*sizeof(double));

'a' is a pointer. 'malloc' creates a new block of uninitialized memory, and returns a pointer to it. Let's call this block of memory 'foo'.

when you say a = malloc, you are saying "I want 'a' to point to 'foo'"

(double[3]){ ... }

Here, you are creating another block of (initialized) memory. Let's call this memory 'bar'

a = (double[3]){ ... }

Here, you are reassigning a. Therefore you are making a point to something else. IE, you are making it point to bar.


So you effectively allocate memory for foo... tell a to point to foo... then immediately have a stop pointing to foo and have it point to bar instead.

Foo is lost, and will be a memory leak, since nothing points to it anymore -- it will be impossible to free().

Thanks for the explanation!
Topic archived. No new replies allowed.