【发布时间】:2013-06-13 01:50:09
【问题描述】:
这个程序应该创建一个动态内存向量。我很确定我正确使用了 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 线有些怀疑......
任何见解将不胜感激,谢谢!
【问题讨论】:
-
不要强制转换malloc的返回值!
-
是 v 应该包含多个 VectorT 还是 VectorT.items 应该包含多个整数?
-
VectorT.items 包含多个整数
标签: c pointers vector struct pointer-address