4

I'm new in c. I want to create array, and after it delete it, and then put another array into it. How can I do it?

2
  • 1
    Can you tell us how you allocated the array? If you used malloc, you can use free to deallocate it, then allocate a new one. Commented May 5, 2011 at 14:52
  • 1
    If you use malloc, you have code. If you have code, you should post it. Commented May 5, 2011 at 15:17

2 Answers 2

7

If you are looking for a dynamic array in C they are fairly simple.

1) Declare a pointer to track the memory,
2) Allocate the memory,
3) Use the memory,
4) Free the memory.

int *ary; //declare the array pointer
int size = 20; //lets make it a size of 20 (20 slots)

//allocate the memory for the array
ary = (int*)calloc(size, sizeof(int));

//use the array
ary[0] = 5;
ary[1] = 10;
//...etc..
ary[19] = 500;

//free the memory associated with the dynamic array
free(ary);

//and you can re allocate some more memory and do it again
//maybe this time double the size?
ary = (int*)calloc(size * 2, sizeof(int));

Information on calloc() can be found here, the same thing can be accomplished with malloc() by instead using malloc(size * sizeof(int));

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

Comments

3

It sounds like you're asking whether you can re-use a pointer variable to point to different heap-allocated regions at different times. Yes you can:

void *p;         /* only using void* for illustration */

p = malloc(...); /* allocate first array */
...              /* use the array here   */
free(p);         /* free the first array */

p = malloc(...); /* allocate the second array */
...              /* use the second array here */
free(p);         /* free the second array */

Comments

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.