在C中初始化一个没有方括号,malloc和calloc的数组

时间:2021-04-08 21:42:21

I was wondering if it was possible to initialize an array without square brackets, malloc or calloc. It's possible to alter and change values with calloc, why not without all this?

我想知道是否可以初始化没有方括号,malloc或calloc的数组。用calloc改变和改变值是可能的,为什么不用这个呢?

void initTab(int * tab, int size) 
{
    for(int i = 0; i < size; i++)
    {
        *(tab + i) = sizeof(int);
    } 
}

This is only an example for editing values in arrays but it doesn't work if the array is not properly initialized.

这只是编辑数组中值的示例,但如果数组未正确初始化则不起作用。

I want to replace this:

我想替换这个:

int * tab = calloc(nb_elements,sizeof(int));

Without calloc.

1 个解决方案

#1


0  

It's certainly possible to use arrays without malloc and calloc because you can make the array be a local or global variable instead of dynamically allocating it. But the syntax for declaring or defining an array always uses square brackets and I don't understand why you need to avoid that kind of syntax. You can have functions that manipulate arrays through pointers, and those functions don't need to use square brackets (and your question has an example of such a function).

当然可以使用没有malloc和calloc的数组,因为你可以使数组成为局部变量或全局变量,而不是动态分配它。但声明或定义数组的语法总是使用方括号,我不明白为什么你需要避免这种语法。你可以拥有通过指针操作数组的函数,这些函数不需要使用方括号(你的问题就是这样一个函数的例子)。

#1


0  

It's certainly possible to use arrays without malloc and calloc because you can make the array be a local or global variable instead of dynamically allocating it. But the syntax for declaring or defining an array always uses square brackets and I don't understand why you need to avoid that kind of syntax. You can have functions that manipulate arrays through pointers, and those functions don't need to use square brackets (and your question has an example of such a function).

当然可以使用没有malloc和calloc的数组,因为你可以使数组成为局部变量或全局变量,而不是动态分配它。但声明或定义数组的语法总是使用方括号,我不明白为什么你需要避免这种语法。你可以拥有通过指针操作数组的函数,这些函数不需要使用方括号(你的问题就是这样一个函数的例子)。