I made the first part of the program, but I don't understand the part of dynamic memory allocation and calculation using pointers. What should I coding? The contents of the program.
my source code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
int num, i;
double dfirst, dlast;
double * x;
/ * Enter the first value, the last value, and the number to divide * /
printf ("Input first, last, total number of x []:");
scanf ("% lf% lf% d", & dfirst, & dlast, & num);
/ * Create after this * /
/ * Allocate memory * /
/ * Determine the value to store.
Be careful not to divide by an integer and decide the number of divisions in consideration of the end value * /
/ * Display results * /
/ * Post-processing * /
return 0;
}
Execution result want to do
% ./a.out
Input first, last, total number of x[]: 0.0 2.0 5
Values of x
0.000 0.500 1.000 1.500 2.000
Values of x^2
0.000 0.250 1.000 2.250 4.000
% ./a.out
Input first, last, total number of x[]: 1.0 2.0 11
Values of x
1.000 1.100 1.200 1.300 1.400 1.500 1.600 1.700 1.800 1.900 2.000
Values of x^2
1.000 1.210 1.440 1.690 1.960 2.250 2.560 2.890 3.240 3.610 4.000
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.