The below code does work and is a test of your code snippet. If something isn't working, it could be a good idea to create a test like this, with hard-coded values for *a3dsFace
, in order to narrow down your problem.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef int Vector3I[3];
typedef uint16_t Lib3dsWord;
struct Lib3dsFace {
/* ... */
Lib3dsWord points[3]; /*! Indices into mesh points list */
/* ... */
};
/* ... */
struct Lib3dsFace some_face = { {0, 1, 2} };
struct Lib3dsFace *a3dsFace = &some_face;
/* ... */
int main(void)
{
Vector3I *theVector = (Vector3I*)calloc(1,sizeof(Vector3I));
(*theVector)[0] = a3dsFace->points[0];
(*theVector)[1] = a3dsFace->points[1];
(*theVector)[2] = a3dsFace->points[2];
printf("theVector: %p, *theVector: %p, &(*theVector)[0]: %p\n", theVector, *theVector, &(*theVector)[0]);
printf("RIGHT Addresses: %p, %p, %p\n", &(*theVector)[0], &(*theVector)[1], &(*theVector)[2]);
printf("WRONG Addresses: %p, %p, %p\n", &*theVector[0], &*theVector[1], &*theVector[2]);
printf("Values: %d, %d, %d\n", (*theVector)[0], (*theVector)[1], (*theVector)[2]);
free(theVector);
return 0;
}
Output:
theVector: 0x1cd3010, *theVector: 0x1cd3010, &(*theVector)[0]: 0x1cd3010
RIGHT Addresses: 0x1cd3010, 0x1cd3014, 0x1cd3018
WRONG Addresses: 0x1cd3010, 0x1cd301c, 0x1cd3028
Values: 0, 1, 2
I put the addresses there so that you can see (*theVector)[0]
is a valid way of accessing the first element of your dynamically allocated Vector3I
.
Perhaps you haven't set a3dsFace->points
properly and that's why {0, 0, 0}
is being copied. Note also that you have each element of a Vector3I
as type int
, and each point is of type uint16_t
. You also don't need to use calloc
to zero the allocated memory, since you're immediately after assigning values to them; you could just use malloc
.
Bottom line is you still haven't provided enough code to find your exact problem, and you should add code to debug your code inside your code.
EDIT: I accidentally had *theVector[0]
which should have been and is now (*theVector)[0]
, since []
has higher precedence than *
. Otherwise it'd cause undefined behaviour due to the fact you're going past the bounds of the array, my bad. I don't know how I forgot that when it was one of the main reasons I was going to post an answer before you made your edit. It worked, but if you ran it through a program like valgrind it'd tell you that something wasn't quite right (even if it may have ran as expected).
As you can see by the addresses outputted above, there's quite a difference. For example having *theVector[1]
, which because of operator precedence is the same as *(theVector[1])
, will mean that it'll increment the address pointed to by theVector
by 3 * sizeof(int)
bytes (aka sizeof(Vector3I)
), instead of just 1 * sizeof(int)
in the (correct) case of (*theVector)[1]
).
Vector3I
? What isa3dsFace->points
? – cnicutar Dec 6 '11 at 20:39a3dsFace
also. – AusCBloke Dec 6 '11 at 21:03