c - 程序没有结束并且什么也没有发生

标签 c

编写一个程序,分为带参数的函数,该程序将加载动态整数数组,直到用户输入数字 0。最初,假设该数组仅包含 5 个这样的数字。如果用户尝试输入的数字超出表可以存储的数量,则程序应检测到这种情况并将其大小再增加 5 个元素。每当表格结束时,程序都应重复上一句中描述的步骤,直到用户完成数字输入。毕竟,程序应该将表的内容写入屏幕并释放分配的内存。

     void fill_array(int *);
void print_array(int *, int);
void *add_memory(int);
int main()
{
    int x;
    int *array_pointer = (int*)calloc(5,sizeof(int));
    if(array_pointer)
    {
        fill_array(array_pointer);
        x = sizeof(array_pointer)/sizeof(array_pointer[0]);
        print_array(array_pointer, x);
    }

    return 0;
}

void fill_array(int *array)
{
    int i = 0, k = 5;
    printf("Please fill an array with at least 5 digits: ");

    while(scanf("%d", &array[i]) != 0)
    {
        if(i > 5)
        {
            k++;
            array = (int*)add_memory(k);

        }
        i++;
    }
}

void *add_memory(int a)
{

    void *array_ptr = realloc(array_ptr,a*sizeof(int));
    return array_ptr;
}

void print_array(int *array, int b)
{
    int i;
    for(i=0;i< b;i++)
        printf("%d ",array[i]);
    puts("");
}

最佳答案

这个函数没有意义:

void *add_memory(int a)
{

  void *array_ptr = realloc(array_ptr, a * sizeof(int));
  return array_ptr;
}

您只能对先前由 malloccalloc 或其他 realloc 分配的指针调用 realloc code> 或 NULL 指针。在您的代码中,array_ptr 尚未初始化,使用未初始化的指针调用 realloc 不会有好的结果。

但是你的程序的整体结构很差,除了答案中的问题之外,肯定还存在其他问题。

关于c - 程序没有结束并且什么也没有发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55067457/

相关文章:

c - 在 MacOSX 上使用 Tcl/Tk C API 时,为什么它会在环境中执行?

c - 如何使用STM32F4从MAX30100读取FIFO数据

c - 数组未正确读取

c++ - 如何在没有 UTF-8 特定代码的情况下解析多语言文档

c++ - fopen 非 ASCII 字符错误

c++ - 这会在没有任何竞争条件的情况下执行吗

c - 在C中通过引用传递多维数组

c - 内存初始化时linux高内核cpu使用率

c++ - 为什么 "volatileQualifiedExpr + volatileQualifiedExpr"在 C 中不一定是 UB 而在 C++ 中是?

c - STM32F103 Timer2不中断