c - 声明数组与为其分配内存

标签 c malloc

我用 C 语言编写了一个函数,它从用户处获取 10 个整数并将其打印出来。

void memoryallocationtest(int number)
{
    // allocate space for 10 integer
    char *input = malloc( 32 * sizeof(char) );
    long *x = malloc( number * sizeof(long) );
    char *ptr;

    printf("please enter 10 integer X consecutively, -2147483648 <= X <= 2147483647)\n");
    /* promts user to enter ith integer
     * converts input string to long value and saves result in x
     */
    for(int i = 0; i < number; i++)
    {
        printf( "%i. Integer:", (i + 1) );
        scanf( "%s", input );
        x[i] = strtol( input, &ptr, 10 );
    }
    free(x);
    free(input);
}

这是一种有效的方法吗?

有没有为我的字符数组“输入”分配和释放空间的点,或者我应该像 char input[32]; 那样声明它?还是这就是隐含发生的事情?

最佳答案

为 10 个整数的数组静态预留内存是这样完成的(数据位于内存的堆栈部分。)

int array[10];

对于动态分配,数据位于堆上。

int *array = (int *) malloc(sizeof(int) * 10);

这是一个简单的图像,大致描述了典型程序的内存布局:

enter image description here

Is there any point of allocating and freeing space for my char-array "input" or should I just declare it like char input[32]; or is that what happens implicit anyway?

动态分配的优点是您无需提前知道要向操作系统请求多少内存。缺点是管理动态分配的内存比较困难,并且更容易受到external fragmentation的影响。 。当您使用 malloc 时,您所描述的不会隐式发生。

如果你事先知道你需要多少内存(你的整数数组到底有多长),就不需要使用动态分配(malloc),也不需要像“char input[32];”这样声明数组。是完全足够的。

关于c - 声明数组与为其分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616750/

相关文章:

C - 结构数组,free 问题,在我的结构数组中赋值的问题

c - C编程:使用malloc,指针和数组

c - 如何从 C 中的新虚拟页分配内存?

c - 复杂多线程代码中的安全网?

c - 哈希表 "Uninitialised value was created by a stack allocation"

c - pthread_cond_wait 2 个线程

c - 如果 bash 脚本不存在,则原子创建文件

c - 如果我尝试存储大于动态分配期间指定的值,为什么 c 编译器不会抛出错误?

c - 此代码如何反转数字中的位?

c - 为什么 realloc() 在 C 中 malloc() 成功的地方失败?