我正在成功循环遍历XML
文件,并在尝试将struct
指针存储到struct's
之前将数据存储到vector
(我认为)。但是当我只能访问最近添加的struct
后,无论我访问哪个索引,我都会立即尝试访问数据。
struct
:
typedef struct
{
double trueHeadingRadians;
double latitude;
double latitudeRadians;
double longitude;
double longitudeRadians;
.
.
} wayPoint;
相关的vector
函数:
typedef struct
{
void **items;
unsigned int capacity;
unsigned int total;
} vector;
// intitiaizes vector struct
void vectorInit(vector* v)
{
v->capacity = VECTOR_INIT_CAPACITY; // 4
v->total = 0;
v->items = malloc(sizeof(void* ) * v->capacity);
}
// resizes vector
static void vectorResize(vector* v, int capacity)
{
void** items = realloc(v->items, sizeof(void* ) * capacity);
if( items )
{
v->items = items;
v->capacity = capacity;
}
}
// returns total number of members in vector
unsigned int vectorTotal(vector *v)
{
return v->total;
}
// adds element to vector
void vectorAdd(vector* v, void* item)
{
if( v->capacity == v->total )
{
vectorResize(v, v->capacity * 2);
}
v->items[v->total++] = item;
}
// gets item from vector
void* vectorGet(vector* v, unsigned int index)
{
if( index >= 0 && index < v->total )
{
return v->items[index];
}
return NULL;
}
现在我在向struct
添加struct
之前向void pointer
添加值。
vector simDataVector;
vectorInit(&simDataVector);
wayPoint pointStruct = {0};
pointStruct.latitude = 37.415000;
.
.
// add struct pointer to vector
vectorAdd(&simDataVector, &pointStruct);
printf("length of vector: %u\n", vectorTotal(&simDataVector));
// THIS IS WHERE I THINK THE ISSUE IS -- AM I DEREFERENCING THIS PROPERLY?
printf("latitude = %f\n", ((wayPoint* )vectorGet(&simDataVector, indx))->latitude);
此输出为:
length of vector: 1 // whichever index I am currently on
latitude = 37.415000 // the most recently added struct's latitude
每次循环都是正确的!矢量可以正确地跟踪大小以及数据。直到初始化之后。当我尝试打印每个wayPoint struct
进行测试时,每个索引都会显示最近添加的wayPoint struct
的数据。我在这里很困惑。
答案 0 :(得分:2)
根据您的矢量实现,您似乎很好地掌握了内存,但是在添加实际数据时忘了复制实际数据。相反,你只是传递了一个指向你的局部变量的指针:
vectorAdd(&simDataVector, &pointStruct);
相反,您需要分配存储空间(给定矢量的当前设计)。也许把它包装在一个函数中:
void wayPointAdd( vector * v, const wayPoint * p )
{
wayPoint * data = malloc( sizeof(wayPoint) );
if( data )
{
*data = *p;
vectorAdd( v, data );
}
}