to create a program that divides two numbers at equal intervals

In C you allocate memory dynamically with the function malloc. This function is quite low-level and the programmer must be very careful to specify the right size of the requested memory. To make the function easier to use it can be convenient to define a macro which also provides error handling:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NEW_ARRAY(ptr, n) \
    (ptr) = malloc((n) * sizeof (ptr)[0]); \
    if ((ptr) == NULL) { \
        fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno)); \
        exit(EXIT_FAILURE); \
    }

With the macro function in place, you can simply add

NEW_ARRAY(x, num);

to your program to allocate an array x of num elements. When you are done with x you free the memory with free(x). In your program you also need to check the result from scanf to make sure the input is valid. Good luck!

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top