[英]Assigning a pointer in a struct to a variable
该程序应该创建一个动态内存向量。 我很确定我正确使用了malloc。 我真正的问题是指针的某些语法,尤其是结构内部的指针。
我正在尝试访问结构内的int指针的地址,以便可以将其分配给另一个指针
我给定的结构是:
typedef struct{
int *items;
int capacity;
int size;
}VectorT;
我想开始使用的功能是:
int getVector(VectorT *v, int index){
int *p;
p = v->items;//(2)
p -= v->size;
p += index;
return *p;
}
假定将项目指针的地址减去列表中项目的数量,然后将所需项目的索引添加到p的地址。 然后,我返回p地址处的内容。
我非常强烈地认为第(2)行不是我需要的语法。
根据到目前为止的尝试,我的程序要么在调用getVector时崩溃,要么输出(我的最佳猜测)某些内存位置。
这是添加向量的代码:
void addVector(VectorT *v, int i){
if(v->size >= v->capacity){
//allocate twice as much as old vector and set old pointer to new address
v = (VectorT *) malloc(2 * v->capacity * sizeof(VectorT));
if(v == NULL){
fprintf(stderr, "Memory allocation failed!\n");//error catch
}
else{
v->capacity *= 2;//double the reported capacity variable
v->size++;//add one to the reported size variable
v->items =(int *) i;//add the item to the vector (A)<-----
}
}
else{
v->size++;//add one to the reported size variable
v->items =(int *) i;//add the item to the vector (B)<-----
}
}
我觉得我的问题不在这里,但是如果是这样,我会对A和B行感到怀疑。
任何见解将不胜感激,谢谢!
至少在以下地方,您处理指针是错误的:
int
覆盖指针。 v->items =(int *) i;
应该
*(v->items) = i;
您的指针算法不正确:减去大小并添加索引将使您在分配的区域的开始之前获得一个指针,这是不正确的。
您正在将malloc
的结果分配给类型为“指向矢量的指针”的局部变量v
。 该分配在调用方中无效,因为指针是通过值传递的。 如果要在addVector
重新确定向量,则应将VectorT **pv
作为第一个参数。 该代码片段看起来并不正确:看来您应该分配v->items=malloc(2 * v->capacity * sizeof(int))
而不是v=malloc(...)
当您执行malloc
,不会释放旧的向量,从而导致内存泄漏。
您需要i的地址,因此:
v->items =&i;//add the item to the vector (A)<-----
另外,在计算尺寸时,您需要:
p -= (v->size*sizeof(int));
更新:
您也可以将指向i的指针传递到getVector中,然后将其保存在v->items
int getVector(VectorT *v, int *index)
//...
v->items = i;
我看到当您应该为VectorT分配内存时,您正在为VectorT分配内存。
void addVector(VectorT *v, int i){
if(v->size >= v->capacity){
//allocate twice as much as old vector and set old pointer to new address
v->items
int* tmp = malloc(2 * v->capacity * sizeof(int));
if(tmp == NULL){
fprintf(stderr, "Memory allocation failed!\n");//error catch
}
else{
int j;
for (j = 0; j < v->size; j++){
tmp[j] = v->items[j];
}
free(v->items);
v->items = tmp;
v->capacity *= 2;//double the reported capacity variable
v->items[v->size] = i;//add the item to the vector (A)<-----
v->size++;//add one to the reported size variable
}
}
else{
v->items[v->size] = i;//add the item to the vector (B)<-----
v->size++;//add one to the reported size variable
}
}
int getVector(VectorT *v, int index){
return v->items[index]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.