0

I am doing ulan sequence in C language. Here based on input values more data will be sored in integer array. I need to create array without size limitation and I have used the code like following for create array without size limitation but it's not working.

int temp_arr[] = {0}, main_arr[] = {NULL}, i, j;

I am used array for do this logic, it's working for small values(1,2) but not working for large values(1001, 1234).

  • 3
    In C, all arrays are fixed size. Your examples above create `temp_arr` and `main_arr` both as 1-element arrays. If you need a variable-sized array, use dynamic memory allocation. – Raymond Chen Nov 26 '16 at 15:34
  • There is a wealth of easily found information about using dynamic arrays in C, found by the simple expedient of typing "dynamic arrays in C" in Google search. How long did you research before posting? – John Coleman Nov 26 '16 at 15:44
  • @Raymond: Here I can't use dynamic memory allocation here, because dynamic memory allocation is used for obtain more space in run time and this also require some size value, my problem is through out the program I don't the size limit. – Premanandh Selvakumarasamy Nov 26 '16 at 15:47
  • That makes little sense. You can keep track of how much memory you have allocated. When your code requires storing something outside of allocated memory (a condition which is easily tested for), you allocate new memory. When this is required -- allocate *more* than you need so that you have a buffer to grow into. – John Coleman Nov 26 '16 at 15:50
  • @John: I spent at least 15 mins to find the solution for my problem and I hope this is not duplicated – Premanandh Selvakumarasamy Nov 26 '16 at 15:53
  • It sounds more like you don't like the solution that you found. C is relatively low level. You are going to need to deal with the complexities of dynamic memory allocation. This is what CPython does under the hood. The functionality of its lists seems to be what you want -- but a Python list is a dynamically allocated C array under the hood, with the interpreter handling any needed reallocation. You don't have an interpreter doing it for you in raw C, so you need to write the code. – John Coleman Nov 26 '16 at 15:57
  • @anandh To add to my previous comment, it seems that perhaps the functionality of R vectors is what you want. You can start with a vector `v` with 100 elements and then just write `v[1000] = 5` and the vector will automatically extend. The R interpreter is written in C -- and implements vectors as dynamically-allocated C arrays. In the above snippet `v[1000] = 5` is going to implicitly involve a call to `malloc`, `calloc` or `realloc`. – John Coleman Nov 26 '16 at 16:09
  • @John: Okay. Will try it – Premanandh Selvakumarasamy Nov 26 '16 at 16:33

0 Answers0