Hi I'm trying to implement malloc into the following file but I am having some difficulty grasping the concept.

My code:

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

#define HALF_PI 1.570639
#define EXPECTED_ARGS 2
#define LOWER_LIMIT 0

float Integrate (float upper_limit, float x[2][10000], float fx[2][10000]);

int main (int argc, char* argv[])
{
	int i;
	float x[2][10000], fx[2][10000], area, dx, upper_limit;
	FILE *input;
	const char input_file[]="px270prog3a.dat";
	
	if (argc != EXPECTED_ARGS)
	{
		printf("Value for upper limit of intergration needed!\n");
		exit (EXIT_FAILURE);
	}
	
	else
	{
		sscanf (argv[1], "%f", &upper_limit);
				
		if ((upper_limit <= 0) || (upper_limit >= HALF_PI))
		{
			printf("Value for Upper Limit is invalid.\n");
			printf("Value for upper limit needs to be between 0 and PI/2\n");
			exit (EXIT_FAILURE);
		}
	}
	
	input = fopen(input_file, "r");
	
	if(input != (FILE*) NULL)
	{
		for(i=0; i<10000; i++)
		{
			fscanf(input, "%f %f\n", &x[0][i], &fx[1][i]);
		}
		fclose(input);
	}
	
	else
	{
		printf("*** Could not open input file! ***\n");
	}
	
	area = Integrate (upper_limit, x, fx);
	
	printf("Area under curve between x=0 and x=%f is:%f\n", upper_limit,area);
	
	return (0);
}

What I need is for any valid file to be the input file and so, the size of the arrays will change, hence my need for use of malloc.
If someone could try to explain this to me it would be greatly appreciated!

First, the arrays have to be pointers so that they can be allocated at runtime. For example: float *x[2]; float * fx[2], Next, after finding the upper_limit (line 26) you can use malloc to allocate the arrays of the proper size

int i;
for(i = 0; i < 2; i++)
{
    x[i] = malloc(upper_limit * sizeof(float));
    fx[i] = malloc(upper_limit * sizeof(float));
}

Thanks for your help! Much easier than the way I was trying to go about it and now I understand malloc a bit!

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.