is it possible in C to do an unfix size array like in Java ?

if so, howto ?


thx guys

Dark

Recommended Answers

All 6 Replies

what do you mean by unfix size array?
in java arrays you'd still need to allocates memory for the elements

can you be more specific or give an example about that?

i know i need to allocate mem and i can`t find my java code, just restarted programming.

the thing is, i don`t know how many entries the users will enter and i don`t remember how i did this in java.

i have 2 things in mind right now.

1) i ask the user how many entries their gonna do, which i`m not even sure it will work, because they don`t even know themselves how many entries they have to do.

2) or i fix the array high enough and i add a counter and transfert only the (counter) number of entries to the db.

but thx for the support, i`m sure i did work on an array that was expanding according to the inputs. i`ll keep searching.


Dark

One common way is to allocate memory in fixed block sizes. When that fills up then allocate a larger array. Here is an example

int array_size = 0; // initial array size
int elements_used = 0; // current number of elements used in the array
int *array = NULL; // initial array is empty

#define BLOCKSIZE 10 // allocate this many elements at a time

int main()
{
   int number = 0;
   for(;;) // infinite loop
   {
      printf("Enter a number\n");
      scanf("%d", &number);
      // check for array overflow
      if( (elements_used+1) >= array_size)
      {      
          // stretch the array
          array_size += BLOCKSIZE;
          array = realloc(array, array_size);
      }
      array[elements_used] = number;
      ++elements_used;
   }
}
commented: helpful tip +1

In short Dynamic allocation

Too bad C doesn't have an ArrayList class like Java or Vector like in C++ ;)

Too bad C doesn't have an ArrayList class like Java or Vector like in C++ ;)

Then it wouldn't be C, would it? :)

LOL ya c is special, i don`t do much of it, but it`s a nice language.

thx guys for the help.


Dark

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.