gpt4 book ai didi

c - 访问 C vector 中的写入违规

转载 作者:行者123 更新时间:2023-11-30 16:23:56 24 4
gpt4 key购买 nike

我正在尝试将一张卡添加到我的 Vect->Items 卡数组中,但在 Items 数组地址的添加中遇到访问写入冲突。 vector 的初始化有问题吗?访问写入冲突发生在初始化 vector 的地址处,但我不明白为什么如果只是初始化就会出错。

void VectorInit(Vector * vect, int capacity)
{
vect->size = 0; //initialize the size to 0 (no elements)
vect->capacity = capacity; //initialize capacity to 10, can grow later


vect->Items = (Card *)malloc(sizeof(Card)* vect->capacity); //alloc mem space for Items array = size of an int * capacity alloted
}

void Grow(Vector * vect)
{
int i;

if (vect->capacity < 0) //if the capacity ever reaches 0 or below, reset it to 10
vect->capacity = 10;
else
vect->capacity *= 2; // 'grow' the capacity by doubling it

Card *newStore = (Card *)realloc(vect->Items, (vect->capacity) * sizeof(Card)); //realloc size for newStore

if (!newStore)
{
newStore = (Card*)malloc(vect->Items, (vect->capacity * sizeof(Card)));

for (i = 0; i < vect->size; ++i)
{
newStore[i] = vect->Items[i]; //copy original values into larger int array
}

free(vect->Items); //free space
vect->Items = newStore; //point items int array to new int ptr
newStore = 0; //best practice
}

}
void Add(Card card, Vector * vect)
{
if (vect->size == vect->capacity) //if the num of elements = capacity, the array is full - Grow it
Grow(vect);
vect->Items[vect->size] = card; //add a provided index and value for insertion in Items array
++vect->size;//increment the size so the pointer points to the next available spot

}

.h

typedef enum {Clubs,Diamonds,Hearts,Spades} Suits;
typedef enum{Deuce = 2,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King,Ace} Face;

typedef struct card
{
Suits suit;
Face face;

} Card;

typedef struct vector
{
Card * Items; //pointer to array of cards
int size; //current num of elements
int capacity; //max num of elements

}Vector;


void VectorInit(Vector * vect, int capacity);
void Grow(Vector * vect);
void Add(Card card, Vector * vect);

main.c

Vector Deck;

VectorInit(&Deck, 52);

Card test;

test.face = (Face)2;
test.suit = (Suits)1;

Add(test, &Deck);

最佳答案

就像人们在评论中所说的那样,您在 if(!newStore) 中执行的代码是多余的,因为 realloc() 失败 malloc() 也可能会失败。主要是您忘记使用 newStore 更新 vect->Items。因此你最终应该得到这样的结果:

void VectorInit(Vector *vect, int capacity) {
vect->size = 0;
vect->capacity = capacity;
vect->Items = malloc(sizeof(Card) * capacity);
}

void Grow(Vector *vect) {
if (vect->capacity < 0) vect->capacity = 10;
else vect->capacity *= 2;

Card *newStore = realloc(vect->Items, vect->capacity * sizeof(Card));
vect->Items = newStore;
}

void Add(Card card, Vector *vect) {
if (vect->size == vect->capacity) Grow(vect);
vect->Items[vect->size++] = card;
}

关于c - 访问 C vector 中的写入违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com