我試圖用c編寫一個使用內存操作的向量。編譯器顯示沒有錯誤,但如果我嘗試從向量打印元素,它只會崩潰。每當我嘗試打印目標變量(printf((int)destination))程序再次崩潰。在C崩潰的向量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct{
void* elemList;
int elemSize;
int maxSize;
int curSize;
}myvector;
void initVec(myvector * vec, int typeSize){
vec->curSize = 0;
vec->maxSize = 10;
vec->elemSize =typeSize;
vec->elemList = malloc(10*sizeof(typeSize));
}
void add(myvector * vec, void* elem){
if(vec->curSize >= vec->maxSize){
vec->elemList = realloc(vec->elemList, vec->maxSize*2);
}
memcpy(&vec->elemList[vec->curSize],elem,vec->elemSize);
}
void get(myvector * vec, int index, void* destination){
if(index > vec->curSize || index < 0){
printf("Invalid Index");
return;
}
destination = malloc(vec->elemSize);
memcpy(destination,&vec->elemList[index], vec->elemSize);
}
int main()
{
myvector newVec;
initVec(&newVec,sizeof(int));
int a = 5;
add(&newVec,&a);
int* b;
get(&newVec,0,b);
printf(*b);//this is where the program crashes
return 0;
}
這仍然是一樣的... –
我明白我所做的指針算術錯誤,但爲什麼目標變量會改變?我的意思是變量b不應該指向另一個方向嗎? –
這裏「目標變量」和「另一個方向」是什麼意思? – MikeCAT