简体   繁体   English

为什么我不能使用malloc设置大于所需大小的数组?

[英]Why can't I use malloc to set array size larger than what is needed?

I am coming from Python so using malloc is new to me. 我来自Python,因此使用malloc对我来说是新的。 Intuitively the below should work but having syntax issues. 直观上,下面的方法应该有效,但是存在语法问题。 In my first line I want to set array size to be a max of 8 ints. 在第一行中,我希望将数组大小设置为最多8个整数。 In the second line, I want to add those 4 ints. 在第二行中,我想添加这4个整数。 This line is for example only, in production I will have user input up to an 8-digit number. 该行仅作为示例,在生产环境中,用户输入的数字最多为8位。 When I go to compile (clang) I get size of array has non-integer type 'void *' If I comment out this first line and initialize with the second line (and adding int type) the code works. 当我去编译(clang)时,我得到size of array has non-integer type 'void *'如果我注释掉第一行并用第二行初始化(并添加int类型),则代码可以工作。 So I am obviously setting the size incorrectly. 所以我显然是错误地设置了尺寸。 Any ideas? 有任何想法吗?

int main(void)

{

    int mult_digits[malloc(8 * sizeof(int))];
    mult_digits[] = {1,2,3,4};
    int size_mult = sizeof mult_digits / sizeof *mult_digits;
    printf("Size of the array is %d\n", size_mult);
    return 0;
}

This code is all wrong. 这段代码是错误的。 You call malloc to allocate memory, and malloc returns a pointer. 您调用malloc分配内存,并且malloc返回一个指针。 Rather than deconstructing your syntax, which is very broken, I'll give a couple of variants of your program. 与其解构语法非常麻烦,不如解构语法,我将给出程序的两个变体。

int main(void)
{
    int mult_digits[] = {1,2,3,4};
    int size_mult = sizeof mult_digits / sizeof *mult_digits;
    printf("Size of the array is %d\n", size_mult);
    return 0;
}

Here the array is not allocated dynamically. 在这里,数组不是动态分配的。 It's a local variable with automatic, stored on the stack. 这是一个自动的局部变量,存储在堆栈中。

For dynamic allocation you would do this: 对于动态分配,您可以这样做:

int main(void)
{
    int *mult_digits = malloc(4*sizeof *mult_digits);
    mult_digits[0] = 1;
    mult_digits[1] = 2;
    mult_digits[2] = 3;
    mult_digits[3] = 4;
    free(mult_digits);
    return 0;
}

The argument to malloc is the number of bytes to be returned. malloc的参数是要返回的字节数。 The value returned is the address of the new block of memory. 返回的值是新内存块的地址。 Note also here that we made a call to free to deallocate the memory. 还要注意这里我们调用了free来释放内存。 If you omit that, the memory will be leaked. 如果您忽略了这一点,内存将被泄漏。

With this variant, there is no way to recover the length of the array from mult_digits . 使用此变体,无法从mult_digits恢复数组的长度。 I know that might freak you out, coming from Python, but I repeat. 我知道这可能会让您感到震惊,它来自Python,但我重复一遍。 There is no way to recover the length of the array from mult_digits . 无法从mult_digits恢复数组的长度。 It's your job to keep track of that information. 跟踪这些信息是您的工作。

Now, you wanted to over-allocate the memory. 现在,您想过度分配内存。 You can certainly do that: 您当然可以这样做:

int main(void)
{
    int *mult_digits = malloc(8*sizeof *mult_digits);
    mult_digits[0] = 1;
    mult_digits[1] = 2;
    mult_digits[2] = 3;
    mult_digits[3] = 4;
    free(mult_digits);
    return 0;
}

Here we only used the first 4 elements, and ignored the final 4. That's just fine. 在这里,我们只使用了前4个元素,而忽略了后4个元素。这很好。 In case you do over-allocate you would typically need to keep track of both the allocated length, and the in-use length. 万一您过度分配,通常将需要同时跟踪分配的长度和使用中的长度。 You can then add new items by increasing the in-use length, up until you reach the allocated length. 然后,您可以通过增加使用长度来增加新项目,直到达到分配的长度为止。 The you need to reallocate a larger block. 您需要重新分配一个更大的块。 I guess that's what you are driving at. 我想这就是你的目标。

The problem is your syntax. 问题是您的语法。 What you meant was: int *mult_digits = malloc(8 * sizeof(int)); 您的意思是: int *mult_digits = malloc(8 * sizeof(int));

After that, mult_digits[] = {1,2,3,4}; 之后, mult_digits[] = {1,2,3,4}; is wrong. 是错的。 You could, however, 但是,您可以

mult_digits[0] = 1;
mult_digits[1] = 2;
mult_digits[2] = 3;
mult_digits[3] = 4;

But unless you have some reason to swim into the pointer deep end, you might just want to: 但是,除非您出于某种原因陷入指针深层,否则您可能只想:

int mult_digits[] = {1, 2, 3, 4};

Edit: to help with applying this answer, here is a full modified function that compiles and runs: 编辑:为帮助应用此答案,这是一个完整的经过修改的函数,可以编译并运行:

#include <stdio.h>

int main(void)
{
    int mult_digits[] = {1,2,3,4};
    int size_mult = sizeof mult_digits / sizeof *mult_digits;
    printf("Size of the array is %d\n", size_mult);
    return 0;
}

in square brackets you must specify the number of elements needed, not the length in byte of the array. 在方括号中,您必须指定所需的元素数,而不是数组的字节长度。 you can use malloc to do 你可以用malloc做

int* multdigits = malloc(sizeof(int)*8);
mult_digits[0] = 1;

etc 等等

(sorry if my syntax is wrong, i don't write c code from years!) (很抱歉,如果我的语法错误,那么我几年都不会写C代码!)

they're two ways to do the same thing. 他们是做同一件事的两种方法。 see "malloc" as the "new" operator. 请参阅将“ malloc”作为“新”运算符。

Try 尝试

int main(void)
{
    int mult_digits[] = {1,2,3,4};
    int size_mult = sizeof mult_digits / sizeof int;
    printf("Size of the array is %d\n", size_mult);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM