整数数组的 malloc 和 realloc 大小

malloc and realloc size of integer array

我希望能够在程序读取数字时重新分配 space 的数量。 例如,当 运行 它应该能够读取任意数量的整数,然后将它们打印为 'Int Array: (all inputs)' 这是我到目前为止尝试过的:

int main(int argc, char **argv)
{
    int i = 0, n, num;
    int *A;

    A = malloc(sizeof(A));

    while(scanf("%d",&num) == 1)
    {
        A[i] = num;
        i++;
    }

    n = sizeof(A)/sizeof(A[0]);

    printf("Int Array: ");
    for (i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }

    return 0;
}

你的代码有一些问题

  1. 语法 int A*; 无效,您的意思是 int *A;
  2. 如果你想分配一个元素正确的语法是

    A = malloc(sizeof(*A));
    
  3. 在这一行

    n = sizeof(A) / sizeof(A[0]);
    

    sizeof() 运算符给出类型的大小,这是一个指针,在这种情况下它与

    相同
    n = sizeof(void *) / sizeof(int);
    

    可以是21

您可以静态设置数组的大小,在这种情况下我建议避免使用 malloc(),或者您可以询问用户,在任何情况下您都无法从指针获取该大小,因此您必须存储它, 例子

if (scanf("%d", &size) != 1)
    return -1;

A = malloc(size * sizeof(*A));
if (A == NULL)
    return -1;
/* proceed to work with `A' and keep `size' somewhere, you need it */
free(A);

您也可以先保留一定数量的内存,即: 如果用户输入超过 10 个项目,你会重新分配另一个内存块,比如 20 个整数,并将最后 10 个项目复制到新块中,依此类推。

size_t block_length = 10;
size_t current_length = 0;
int *A = malloc(sizeof(int) * block_length); // to store 10 integer
if (A == NULL)
    doNotContinue_AllocationFailure();
current_length += block_length;
// ... input the first ten numbers, check if count numbers is lesser
// than block_length
void *ptr;
ptr = realloc(A, sizeof(int) * (block_length + current_length)
if (ptr == NULL)
 {
    free(A); /* Otherwise a memory leak occurs */
    doNotContinue_AllocationFailure();
 }
A = ptr;

// A can now hold up to 20 numbers, and you can input the next 10 numbers

一个技巧是在每个新输入中重新分配内存。

 int indefiniteInput() {

    int num;
    int index = 0;
    int *inputs = malloc(sizeof (int));

    if (inputs == NULL) {
        perror("malloc failed!");
        return -1;
    }

    printf("Input numbers: ");

    while(scanf("%d", &num) == 1) {

        // stops getting inputs when -1 is entered, 
        // you can change it to any value you want
        if (num == -1)
            break;

        // reallocates memory for the input
        int *temp = realloc(inputs, sizeof (int) * (index + 1));

        if (temp == NULL) {
            free(inputs);
            perror("realloc failed!");
            return -1;
        }

        inputs = temp;  

        // adds the last input to reallocated memory
        inputs[index++] = num;
    }

    printf("Stored inputs: ");

    int i = 0;
    for (; i < index; i++)
        printf("%d ", inputs[i]);

    free(inputs);
    return 0;
}

输出:

Input numbers: 5 6 7 8 9 -1
Stored inputs: 5 6 7 8 9 -1

Input numbers: 1 2 3 5 -5 -6 89 256 2001 45600 96 33 369 -1
Stored inputs: 1 2 3 5 -5 -6 89 256 2001 45600 96 33 369