所以我的代码假设将数字插入动态数组,如果需要更多容量,则向数组添加更多容量,从数组中删除数字,然后确保唯一的 NULLS 出现在数组的末尾。它还告诉用户数组中有多少个数字以及数组的总大小是多少。我的问题是当我从数组中删除一个数字时,它有时会打印出我的数组中有一个数字 -33686019。这不会发生太多,但我根本不希望它发生。
#include <stdio.h>
#include <iostream>
int* gArray = NULL;
int gSize = 0;
int gCapacity = 0;
void Insert(int value);
void Remove(int value);
void Resize(int newCapacity);
void Print(void);
void main()
{
int input = 0;
while(input != 3)
{
printf(">=== Dynamic Array ===\n");
printf("What do you want to do?\n");
printf("1. Insert\n");
printf("2. Remove\n");
printf("3. Quit\n");
printf("Your choice: ");
scanf_s("%d", &input);
printf("\n\n");
int value = 0;
switch(input)
{
case 1:
{
printf("Enter a number: ");
scanf_s("%d", &value);
Insert(value);
Print();
break;
}
case 2:
{
printf("Enter number you wish to delete: ");
scanf_s("%d", &value);
Remove(value);
Print();
break;
}
case 3:
{
break;
}
default:
{
printf("Invalid selection\n");
}
}
}
}
void Insert(int value)
{
bool valueSet = false;
while(valueSet == false)
{
if(gArray == NULL)
{
Resize(1);
gArray[gSize] = value;
++gSize;
valueSet = true;
}
else if(gArray[gCapacity] == NULL)
{
gArray[gSize] = value;
++gSize;
valueSet = true;
}
else if(gArray[gCapacity] != NULL)
{
Resize((gCapacity + 1));
gArray[gSize] = value;
++gSize;
valueSet = true;
}
}
}
void Resize(int newCapacity)
{
int* tempArray = new int[newCapacity];
std::copy(gArray, gArray+(newCapacity-1), tempArray);
gArray = new int[newCapacity];
std::copy (tempArray, tempArray+(newCapacity-1), gArray);
gCapacity = newCapacity;
}
void Remove(int value)
{
for(int i = 0; i < gCapacity; ++i)
{
if(gArray[i] == value)
{
gArray[i] = NULL;
--gSize;
}
}
for(int i = 0; i < gCapacity; ++i)
{
if(gArray[i] == NULL)
{
gArray[i] = gArray[(i + 1)];
gArray[(i + 1)] = NULL;
}
}
}
void Print(void)
{
printf("Array contains: ");
for(int i = 0; i < gCapacity; ++i)
{
if(gArray[i] != NULL)
{
printf("%d, ", gArray[i]);
}
}
printf("size = %d, capacity = %d\n", gSize, gCapacity);
}