Jackie
Jackie

Reputation: 23477

Dynamically Size Array in C

So If I have something that was Dynamic (IE iterated through a for loop) similar to this...

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

And I wanted to create an array of size SCREENWIDTH and add entries to it. Is there a way I can do this?

so PSUEDO wise it would be...

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

Upvotes: 0

Views: 1031

Answers (2)

Kranthi Kumar
Kranthi Kumar

Reputation: 1264

In C you can create dynamic array using 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.

Example: In your case you can access only from e[0] to e[SCREENWIDTH-1].

So, please correct your loop by making it i < SCREENWIDTH. So, it will be

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

Upvotes: 0

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158449

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") ;
   }
}

Upvotes: 2

Related Questions