Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调整数组大小的函数不工作[C]_C_Arrays_Resize - Fatal编程技术网

调整数组大小的函数不工作[C]

调整数组大小的函数不工作[C],c,arrays,resize,C,Arrays,Resize,这是一个以学习为目的的课程。 我试图在程序运行时增加一个数组大小,直到它的大小等于12。但我有一个错误,我不知道为什么。谢谢你的帮助 #include <stdlib.h> #include <stdio.h> void incrementSize(int **arr, int *currentSize); void swap(int **a, int **b); void main() { int i = 0, size = 3; i

这是一个以学习为目的的课程。 我试图在程序运行时增加一个数组大小,直到它的大小等于12。但我有一个错误,我不知道为什么。谢谢你的帮助

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

void incrementSize(int **arr, int *currentSize);
void swap(int **a, int **b);

void main() {
    int i = 0,
        size = 3;
    int *array = (int*)malloc(size * sizeof(int));

    while (size < 12) {
        if (i == size) //If the logical size is equal to the physical size increment the size of the array.
            incrementSize(&array, &size);

        array[i] = i + 1;
        i++;
    }

    for (int j = 0; j < size; j++) //Prints the array
        printf("%d ", array[j]);
    printf("\n");
}
还编写了这个函数来交换两个给定数组的地址

void swap(int **a, int **b)
{
    int* tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

realloc
实际
free
s由给定指针指向的存储

如果内存不足,则旧内存块不会被释放,并且 返回空指针

如果参数为NULL,则行为与调用
malloc(新大小)
相同


您编写的代码将释放内存

在C语言中,你不应该强制转换malloc的返回。你得到了什么错误?只是一个没有任何具体说明的错误。没有这样的事情。使用-g标志集编译,并通过调试器和valgrind运行它,然后让我们知道错误。
void swap(int **a, int **b)
{
    int* tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}