动态内存分配在C没有的malloc [英] Dynamic memory allocation in c without malloc

查看:176
本文介绍了动态内存分配在C没有的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个C程序我的一个朋友写了。
据我所知,有数组在编译时被初始化之前C99推出VLA的,或者使用的malloc 运行时。

但这里的程序接受一个常量从用户的价值,并相应地初始化数组。
它的正常工作,甚至与的gcc -std = C89 ,但看起来非常错误的我。
它是所有编译器相关的?

 的#include<&stdio.h中GT;INT
主要()
{
 INT常量N;
 scanf函数(%d个,&安培; N);
 的printf(N为%d \\ N,N);
 INT ARR [N];
 INT I;
 对于(i = 0; I< N;我++)
   改编[我] =我;
 对于(i = 0; I< N;我++)
   的printf(%d个,编曲[I]);
 返回0;
}


解决方案

添加 -pedantic 来你的编译选项(例如, -Wall -std = C89 -pedantic )和 GCC 会告诉你:

警告:ISO C90禁止变长数组'改编'

这意味着你的程序的确不是C89 / C90标准。

更改为 -pedantic -pedantic-错误 GCC 将停止翻译。

Here's a C program one of my friends had written. From what I know, arrays had to be initialised at compile time before C99 introduced VLA's, or using malloc during runtime.

But here the program accepts value of a const from the user and initialises the array accordingly. It's working fine, even with gcc -std=c89, but looks very wrong to me. Is it all compiler dependent?

#include <stdio.h>

int
main()
{
 int const n;
 scanf("%d", &n);
 printf("n is %d\n", n);
 int arr[n];
 int i;
 for(i = 0; i < n; i++)
   arr[i] = i;
 for(i = 0; i < n; i++)
   printf("%d, ", arr[i]);
 return 0;
}

解决方案

Add -pedantic to your compile options (e.g, -Wall -std=c89 -pedantic) and gcc will tell you:

warning: ISO C90 forbids variable length array ‘arr’

which means that your program is indeed not c89/c90 compliant.

Change with -pedantic with -pedantic-errors and gcc will stop translation.

这篇关于动态内存分配在C没有的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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