1
  • Does realloc function in C allocate contiguous memory space?

  • I am trying to implement dynamic integer array. Should I increment pointer by size of array element or by 1?

  • Are there any other better ways to implement dynamic array in C?

1
  • Do you mean "contiguous with the original memory"? Commented Jan 31, 2014 at 20:23

2 Answers 2

2
  1. Yes, just like malloc() does.

  2. If you have an int* ptr which is a pointer to an element of a dynamically allocated int array, a simple ptr++ will point to the next element.

  3. Using malloc() and realloc() in C seems to me a good option for dynamic arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

My comment above also applies here.
1

Does realloc function in C allocate contiguous memory space?

Yes.

I am trying to implement dynamic integer array. Should I increment pointer by size of array element or by 1?

You should increase your pointer by 1.

Are there any other better ways to implement dynamic array in C?

Using malloc family functions is the only way. But in C99 and latter you can use variable length arrays (but it has some limitations as it allocates memory on stack).

3 Comments

Thanks for quick reply! I need to change my code now!
@user3224177; What change?
Doesn't make sense to increment size by size of a pointer, it should double the memory or, better, increase it by 150%. It gives the amortized constant time for append! And, yes, the best way in C is using realloc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.