该程序应该创建一个动态内存向量。 我很确定我正确使用malloc。 我真正的问题是一些带指针的语法,特别是结构中的指针。
我正在尝试访问结构中的int指针的地址,所以我可以将它分配给另一个指针
我给出的结构是:
typedef struct{ int *items; int capacity; int size; }VectorT;
而我正在努力工作的function是:
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)size++;//add one to the reported size variable v->items =(int *) i;//add the item to the vector (B)<----- } }
我不觉得我的问题在这里,但如果是的话,我对A和B行有一些怀疑……
任何见解都将非常感谢,谢谢!
你至少在这些地方处理指针是错误的:
v->items =(int *) i;
应该
*(v->items) = i;
你想要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.items分配内存时,我看到你正在为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] }
以上就是c/c++开发分享将结构中的指针分配给变量相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/549350.html