【问题标题】:malloc and realloc size of integer array整数数组的 malloc 和 realloc 大小
【发布时间】:2015-06-01 04:01:57
【问题描述】:

我希望能够在我的程序读取数字时重新分配空间量。 例如,在运行时,它应该能够读取任意数量的整数,然后将它们打印为“Int Array:(所有输入)” 这是我迄今为止尝试过的:

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;
}

【问题讨论】:

  • int A* 无效!
  • 另外,sizeof A 通常给你 4 或 8,即指针的大小,而不是它指向的数据的大小。

标签: c arrays malloc


【解决方案1】:

你的代码有问题

  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);

【讨论】:

  • 哦,好吧,所以它不可能在用户输入时改变大小?所以你必须事先询问用户或设置尺寸?
  • 如果我要预先设置一个大小,我将如何使用 realloc 将其限制为用户输入的元素数量。所以我可以打印出每个 int e.g.(for (i = 0; i
【解决方案2】:

您也可以先保留特定数量的内存,即: 如果用户输入了超过 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

【讨论】:

    【解决方案3】:

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

     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
    

    【讨论】:

    • 不要这样使用realloc()!并且始终认为更糟的情况会发生,因此您要防止不被阻止,就像 malloc() 可能会返回 NULL
    猜你喜欢
    • 2018-08-29
    • 2017-08-24
    • 2021-05-05
    • 2012-09-19
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2017-06-15
    • 2012-03-17
    相关资源
    最近更新 更多