gpt4 book ai didi

c - 堆栈上的动态内存分配

转载 作者:太空狗 更新时间:2023-10-29 17:27:20 24 4
gpt4 key购买 nike

我最近尝试了这个实验,在这个实验中,我没有为未知大小的内存需求进行动态内存分配,而是进行了静态分配。当我声明数组 a[i] 时,我保留了 i(数组的大小)变量并依赖于用户提供的输入。

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
void function(int );
int main(void)
{
int i;
printf("Enter:");
scanf("%d",&i);
function(i);
printf("i = %d\n",i);
getch();
return 0;
}
void function(int i)
{
char a[i];
char b[4];
strncpy(a,"hello",i);
strcpy(b,"world");
int j = 0;
char *c = a;
for( j = 0; j< 20; j++ )
printf("%c",*c++);
}

我的问题是:

  • 这样的操作合法吗?
  • 如果不是,为什么编译器不发出任何警告或错误?
  • 内存分配到哪里:栈还是堆?
  • 为什么 ANSI C/GCC 允许这样做?

最佳答案

Is such an operation legal?

它叫做变长数组。

VLA 在 ANSI C99 中是合法的,并且作为一些 C99 之前的编译器的扩展。 GCC 支持它作为严格的 C99 和非 C99 代码的扩展。它在 C++0x 中也是合法的。

If no, why does the compiler not issue any warning or error?

使用 gcc:

$ gcc -std=c89 src/vla.c  -Wall -ansi -pedantic
src/vla.c: In function ‘function’:, not dynamic array.
src/vla.c:17: warning: ISO C90 forbids variable length array ‘a’
src/vla.c:21: warning: ISO C90 forbids mixed declarations and code

来自 MSDOS 的 'conio.h' 的存在表明您可能正在使用 Microsoft Visual C++ 编译器,所以不要担心。 MS 致力于使他们的编译器更符合 C++0x 标准,但没有声明其 C 编译器模式的标准。你问的是为什么法语词典中没有西类牙语方言词。

Where will this memory be allocated: Stack or heap?

它是一个自动对象,因此出于效率原因,大多数 C 实现将放入堆栈中。

Why does ANSI C/GCC allow this

它对于在运行时创建可变大小的临时数组很有用,其生命周期不会超出函数调用。

关于c - 堆栈上的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1653816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com