Home > Software design >  how to print all the elements of a dynamic array? and find the minimum value
how to print all the elements of a dynamic array? and find the minimum value

Time:10-03

I have a dynamic array of int in a Struct and I want to print() all the elements in that array.

and also retrieve the minimum value, since I don't know the size of the array, I don't know how to do it.

Can you help me.

CodePudding user response:

since I don't know the size of the array, I don't know how to do it.

You must know the size of your array. Your struct should contain the size of that array:

struct your_struct {
    // fields...
    
    int *array; // Your dynamic array
    int size;   // Your array size
};

In order to print any array (not just dynamically allocated arrays), you can define a function that does that for you:

void print_array(int *array, int size, const char *sep)
{
    int i;
    for (i = 0; i < size; i  )
        printf("%d%s", array[i], sep);
}

sep allows you to specify how to separate your array's elements. It could be a space , a dash -, a coma ,, a bar |, etc.

To get the minimum value, you can also implement a function that does that for you:

// Assuming size > 0
int array_min(int *array, int size)
{
    int min = array[0];
    int i;
    for (i = 1; i < size; i  )
        if (min > array[i])
            min = array[i];

    return min;
}
  •  Tags:  
  • c
  • Related