相关疑难解决方法(0)

使用 realloc 扩展和收缩数组

我正在尝试编写一个程序,该程序首先为 100 个 int 元素动态初始化一个队列数组。每当队列已满并且另一个元素应该排队时,原始数组应该将其大小加倍,以便可以插入新元素。如果元素出队,并且队列包含的元素数量低于其实际大小的一半,则应该将队列大小减半。但是,它的大小永远不应低于 10。

我正在尝试使用 realloc 扩展和收缩数组,但是我在理解其机制时遇到了一些问题,尤其是在返回新指针时。下面是我的程序(有一些冗余printfdebugging原因):

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <iso646.h>   



void enqueue(int arr[], int* lastElementIdx, int *length, int element);
int dequeue (int arr[], int* lastElementIdx, int *length);
void printQueue(const int arr[], int lastElementIdx);
int expandArray(int *arr, int length);
int shrinkArray(int *arr, int length, bool min);


void test1(int *arr, int* lastElementIdx, int *length)
{
    int* temp = arr;
    printf("\nprintQueue #1:\n");                   //print queue, should be empty
    printQueue(temp, *lastElementIdx);

    for(int i = …
Run Code Online (Sandbox Code Playgroud)

c arrays pointers realloc

1
推荐指数
1
解决办法
3003
查看次数

标签 统计

arrays ×1

c ×1

pointers ×1

realloc ×1