简体   繁体   English

C语言中的动态大小数组

[英]Dynamically Size Array in C

So If I have something that was Dynamic (IE iterated through a for loop) similar to this... 所以,如果我有一些动态的东西(IE迭代通过for循环)类似于这个...

for (i=0; i <= SCREENWIDTH; i++)
{
}

And I wanted to create an array of size SCREENWIDTH and add entries to it. 我想创建一个大小为SCREENWIDTH的数组并向其添加条目。 Is there a way I can do this? 有没有办法可以做到这一点?

so PSUEDO wise it would be... 所以PSUEDO明智的是......

int[SCREENWIDTH] e = {1,2,....SCREENWIDTH}
for (i=0; i <= SCREENWIDTH; i++)
{
  e[i]= i;
}

You can do this like so: 你可以这样做:

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

int main()
{
   int SCREENWIDTH = 80 ;
   int *arr = (int *)malloc( sizeof(int) * SCREENWIDTH ) ;

   if( NULL != arr )
   {
      for( int i = 0; i < SCREENWIDTH; ++i )
      {
         arr[i] = i ;
      }

      for( int i = 0; i < SCREENWIDTH; ++i )
      {
         printf( "%d, ", arr[i]) ;
      }
      printf("\n") ;
   }
}

In C you can create dynamic array using malloc. 在C中,您可以使用malloc创建动态数组。 Example in your case: 你案例中的例子:

int * e = (int*)malloc(SCREENWIDTH*sizeof(int));

Once you allocate memory dynamically in this way. 一旦以这种方式动态分配内存。 The next think you can do is initialization of the array using the loop. 接下来你可以做的是使用循环初始化数组。

There is a mistake the way you are accessing the loop. 您访问循环的方式有误。 In C The indexing starts from 0 to n-1. 在C中索引从0开始到n-1。

Example: In your case you can access only from e[0] to e[SCREENWIDTH-1]. 示例:在您的情况下,您只能从e [0]到e [SCREENWIDTH-1]进行访问。

So, please correct your loop by making it i < SCREENWIDTH. 所以,请通过使我<SCREENWIDTH来纠正你的循环。 So, it will be 所以,它会

int *e =  (int*)malloc(SCREENWIDTH*sizeof(int));
for (i=0; i < SCREENWIDTH; i++)
{
  e[i]= i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM