代码:
/* 动态数组 */
struct DYNAMICARRAY
{
int *pAddress;
int size;
int capacity;
};
DYNAMICARRAY *initialDynamicArray()
{
DYNAMICARRAY *p = (DYNAMICARRAY *)malloc(sizeof(DYNAMICARRAY));
p->size = 0;
p->capacity = 5;
p->pAddress = (int *)malloc(sizeof(int) * p->capacity);
return p;
}
void push_back(DYNAMICARRAY *p, int b)
{
if (p == NULL)
{
return;
}
if (p->size == p->capacity)
{
int *newArray = (int *)malloc(sizeof(int) * p->capacity * 2);
for (int i = 0; i < p->size; i++)
{
newArray[i] = p->pAddress[i];
}
free(p->pAddress);
p->capacity = p->capacity * 2;
p->pAddress = newArray;
}
p->pAddress[p->size] = b;
p->size++;
}
void print_arrary(DYNAMICARRAY *p)
{
if (p == NULL)
{
return;
}
for (int i = 0; i < p->size; i++)
{
cout << p->pAddress[i] << endl;
}
cout << “mArray size=” << p->size << endl;
cout << “mArray capcitory” << p->capacity << endl
<< endl;
}
void free_mArray(DYNAMICARRAY *p)
{
if (p == NULL)
{
return;
}
free(p->pAddress);
free§;
p = NULL;
}
int find_mArray_by_value(DYNAMICARRAY *p, int b)
{
if (p == NULL)
{
return -1;
}
int pos = -1;
for (int i = 0; i <= p->size; i++)
{
if (b == p->pAddress[i])
{
pos = i;
// cout << “in find_mArray_by_value”
// << “i=” << i << " pos=" << pos << endl;
break;
}
if (i == p->size)
{
cout << “can’t find_mArray_by_value” << endl
<< endl;
break;
}
}
return pos;
}
void remove_by_value_in_array(DYNAMICARRAY *p, int b)
{
if (p == NULL)
{
return;
}
int pos = find_mArray_by_value(p, b);
for (int i = pos; i <= p->size; i++)
{
if (i == p->capacity)
{
p->pAddress = NULL;
p->size -= 1;
break;
}
p->pAddress[i] = p->pAddress[i + 1];
}
p->size -= 1;
}
void remove_by_position_in_array(DYNAMICARRAY *p, int b)
{
if (p == NULL)
{
return;
}
int pos = b;
for (int i = pos; i <= p->size; i++)
{
if (i == p->capacity)
{
p->pAddress = NULL;
p->size -= 1;
break;
}
p->pAddress[i] = p->pAddress[i + 1];
}
p->size -= 1;
}
void test07()
{
DYNAMICARRAY *mArry = initialDynamicArray();
cout << “--------print mArray before any change--------” << endl;
print_arrary(mArry);
for (int i = 0; i < 15; i++)
{
push_back(mArry, i);
}
cout << “--------print mArray after insert 0~15 --------” << endl;
print_arrary(mArry);
cout << "--------查找数值8,在动态数组中的位置 --------" << endl;
int val = 8;
int pos = 0;
pos = find_mArray_by_value(mArry, val);
cout << "value:" << val << " at pos " << pos << endl
<< endl;
cout << "--------删除数值9--------" << endl;
remove_by_value_in_array(mArry, 9);
print_arrary(mArry);
cout << "--------删除位置0上的数值--------" << endl;
remove_by_position_in_array(mArry, 0);
print_arrary(mArry);
free_mArray(mArry);
}
extern “C” void app_main(void)
{
test07();
}
结果: