动态数组使用malloc和realloc? [英] Dynamic array using malloc and realloc?

查看:137
本文介绍了动态数组使用malloc和realloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个接一个地收集输入整数。我的数组以大小1开头,我想将其扩展为1,并收集每个输入(这样做很明智吗?)

I'm trying to collect input integers one by one. My array starts with size 1 and I want to expand it by 1, with every input collected (is this a smart thing to do?)

无论如何,这是代码我设法提出来了,但是它没有按预期工作。

Anyway, this is the code I managed to come up with, but it's not working as intended.

在此过程之后,sizeof(array)始终返回8,我认为这意味着该数组只是调整大小一次。 (sizeof(int)是4位)

After this process, sizeof(array) always returns 8, which I assume means that the array is only being resized once. (sizeof(int) is 4 bits)

尝试输出数组会导致第一个输入变量的多个实例。

Trying to output the array results in multiple instances of the first input variable.

输出代码

for(int s=0;s<sizeof(array)/sizeof(int);s++){
    printf("%i\n",array[i]);
}

原始代码:

    int i;
    int size = 1;
    int *array = malloc(size * sizeof(int));
    int position = 0;

    do{
        i = getchar() - 48;
        f (i != -16 && i != -38 && i != 0) {
            array[position] = i;

            position++;
            size++;
            *array = realloc(array, size * sizeof(int));
        }
    } while (i != 0);

更新后仍无法使用代码

    int i;
    int size = 1;
    int *array = malloc(size * sizeof(int));
    int position = 0;

    do{
        i = getchar() - 48;
        f (i != -16 && i != -38 && i != 0) {
            array[position] = i;

            position++;
            size++;
            array = realloc(array, size * sizeof(int));
        }
    } while (i != 0);


推荐答案

(并附上我的评论:) sizeof(array)返回8,因为它等于 sizeof(int *) array 的类型为 int * ),其值为8(您可能将其编译为64位)。 sizeof 不适用于数组指针。

(With some copy-paste from my comment:) sizeof(array) returns 8 because it equals sizeof(int*) (array is type int*) which is 8 (you're probably compiling as 64-bit). sizeof doesn't work how you think for pointers to arrays.

类似地,您的输出代码是错误的,因为同样的原因。您只打印前两个元素,因为 sizeof(array)/ sizeof(int)始终为 8/4 = 2

Similarly, your output code is wrong, for the same reason. You only print the first two elements because sizeof(array)/sizeof(int) will always be 8/4=2. It should be

for(int s=0;s<size;s++){
    printf("%i\n",array[s]);
}

(请注意还更改了索引变量 i s
,其中 size 是其他代码块中的变量。如果数组是使用指针动态分配的,则无法从 sizeof 中找到数组的长度;这不可能。您的代码必须记住数组的大小。

(note also changed index variable i to s) where size is the variable from your other code chunk(s). You cannot find the length of the array from sizeof if it's dynamically allocated with pointers; that's impossible. Your code must "remember" the size of your array.

这篇关于动态数组使用malloc和realloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆