hi guys,

i am not able to declare the array dynamically in c will you help me out thanks

Recommended Answers

All 4 Replies

What did you try? While it's straightforward, the exact method depends on the result you want.

hi
actully i want to impliment stack in c using array and i want to double the size of array as it fills completely so please help me out

For dynamically sized arrays in C, your friend is the realloc() function. But instead of int a[5], you must use int *a = malloc(5 * sizeof(int));. Only then can you use the realloc() function to resize the array. In other words...

int *Array = (int *) malloc(3 * sizeof(int));  // Create an array with 3 ints

Array[0] = 11;
Array[1] = 250;
Array[2] = 7;

// Now I want to increase its size...

Array = (int *) realloc(Array, 5 * sizeof(int));  // I've now reallocated the array to 5 ints

Array[3] = 9;
Array[4] = 999;

Reallocating should only be done when absolutely necessary. This is because there is a highly possible performance hit using this function as it needs to find a place in memory where the data can fit. In other words, if the array cannot grow in its place, realloc() will find a new place and copy the data to the new place. Doing this too much can be costly in clock cycles.

Just a small addition to the above post.
When ever you declare arrays dynamically you must

int main()
{
        int *arr =(int *)malloc(sizeof(int)*10);

        if(!arr){
                // Check if you did get the memory you asked for
                printf("No memory. Terminating program\n");
                exit(1);
        }
        else{
                printf("Sufficient memory found\n");
        }

        // Do operation on the array here

        free(arr);                     // Free the memory that was given to you after you are done using it 
        return 0;
}
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.