C语言中malloc动态分配空间的使用

求解答,我看不出来怎么解决,谢谢!

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    int count, *array;
    if ((array(int *)malloc (10 * sizeof(int))) == NULL)
    {
        printf("can not success!\n");
        exit(1);
    }
    for (count = 0; count < 10; count++)
        array[count] = count;
    for (count = 0; count < 10; count++)
        printf("%2d ", array[count]);
    return 0;
}

虽然基本问题只是少了个等号,但希望楼主学到的不只是语法,而是 C 语言的风格与习惯,以下逐步地指出能改善的地方:

1. array后方少了个等号

if ((array = (int *)...

2. C99 版本后,不建议将malloc返回值转换,因此这样写即可:

 if ((array = malloc...

请参考 Do I cast the result of malloc?

3. NULL的判断可利用 Logical NOT 运算符 (即惊叹号 !) 来省略:

if (!(array = malloc(...

4. 名称 count 一般不会用于 for loop 的计数器,而是使用常见的 i (index)

请参考 Linux Coding Style

5. 同上,count, len, size... 等名称适合用于指出数组大小

6. 英文中,cannot 是较常规的写法


总结以上代码:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    int count = 10;
    int i, *array;
    if (!(array = malloc(count * sizeof(int)))) {
        printf("cannot success!\n");
        exit(1);
    }
    for (i = 0; i < count; i++)
        array[i] = i;
    for (i = 0; i < count; i++)
        printf("%2d ", array[i]);

    return 0;
}

1. if判断语句中的内存申请方式不正确。需要一个指针去指向(保存)malloc申请的内存空间地址,不然是无法使用申请的这个内存空间的。代码如下:

 if ((array = (int *)malloc(10 * sizeof(int))) == NULL)
    {
        printf("can not success!\n");
        exit(1);
    }

2. malloc申请的内存空间,默认是不会初始化操作的(即清零),因此申请到的40字节内存空间是一些垃圾值。最好是在array申请成功之后,使用memset对其清零操作。


浪费我时间, 回答居然不采纳??????


不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^