c/c++语言开发共享如何在C中声明运行时数组的大小?

我基本上想要相当于这个的C(嗯,只是数组的部分,我不需要类和字符串解析和所有这些):

public class Example { static int[] foo; public static void main(String[] args) { int size = Integer.parseInt(args[0]); foo = new int[size]; // This part } } 

原谅我的C无知。 我被java损坏了;)

     /* We include the following to get the prototypes for: * malloc -- allocates memory on the freestore * free -- releases memory allocated via above * atoi -- convert a C-style string to an integer * strtoul -- is strongly suggested though as a replacement */ #include  static int *foo; int main(int argc, char *argv[]) { size_t size = atoi(argv[ 1 ]); /*argv[ 0 ] is the executable's name */ foo = malloc(size * sizeof *foo); /* create an array of size `size` */ if (foo) { /* allocation succeeded */ /* do something with foo */ free(foo); /* release the memory */ } return 0; } 

    警告:关闭袖口,没有任何错误检查。

    在C中,如果忽略错误检查,则可以使用此方法:

     #include  static int *foo; int main(int argc, char **argv) { int size = atoi(argv[1]); foo = malloc(size * sizeof(*foo)); ... } 

    如果您不想使用全局变量并且使用C99,则可以执行以下操作:

     int main(int argc, char **argv) { int size = atoi(argv[1]); int foo[size]; ... } 

    这使用VLA – 可变长度数组。

    如果需要初始化数据,可以使用calloc:

     int* arr = calloc (nb_elems, sizeof(int)); /* Do something with your array, then don't forget to release the memory */ free (arr); 

    这样,分配的内存将用零初始化,这可能很有用。 请注意,您可以使用任何数据类型而不是int。

    不幸的是,这个问题的许多答案,包括已接受的答案都是正确的,但不等同于OP的代码片段 。 请记住, operator new[]为每个数组元素调用默认构造函数。 对于像int这样没有构造函数的POD类型,它们是默认初始化的(读取:零初始化,参见C ++标准的 §8.5¶5-7)。

    我刚刚为calloc交换了malloc (分配未初始化的内存)(分配归零的内存),所以相当于给定的C ++代码段将是

     #include  /* atoi, calloc, free */ int main(int argc, char *argv[]) { size_t size = atoi(argv[1]); int *foo; /* allocate zeroed(!) memory for our array */ foo = calloc(sizeof(*foo), size); if (foo) { /* do something with foo */ free(foo); /* release the memory */ } return 0; } 

    很抱歉恢复这个老问题,但是如果没有评论(我没有所需的代表)就感觉不对;)

     int count = getHowManyINeed(); int *foo = malloc(count * sizeof(int)); 

      以上就是c/c++开发分享如何在C中声明运行时数组的大小?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/545569.html

      (0)
      上一篇 2021年1月10日
      下一篇 2021年1月10日

      精彩推荐