Chris Johnson wrote:
I've got a program that has two functions, and both need to access an
array. However, the size of the array is not even defined until I'm
partially through the main() function. Here's a quick demonstration of
what I need:
#include <stdio.h>
#include <stdlib.h>
void fubar(int,int);
// This is the array I want to make available to both functions
int equation[count];
int main()
{
int y, count = 0;
while(scanf("%d",&y) != EOF)
count++;
fubar(y,count);
printf("%d\n",equation[0]);
}
void fubar(int y, int count)
{
int i;
for(i = 0; i < count; i++)
equation[i] = y;
}
Effectively what I need is to be able to declare global variables within a
function. Is that possible? Or else is there a workaround?
First of all you do not need a global varialbe to do this. You can
use pointer arguments to modify variables.
Since you are modifying the array length, you can use dynamic
allocations to allocate the size as you need it.
For example, you could prototype the function fubar to:
int fubar(int **y, size_t *count, int value);
where y is a pointer to a pointer to the dynamic allocated array.
count is a pointer to a count of elements
and value is the value you wish to insert in the array.
The Function returns an int that will indicate success or failure
of the allocation.
Here is a working example using function realloc to do the allocations.
#include <stdio.h>
#include <stdlib.h>
int AddArray(int **array,size_t *count,int value);
int main(void)
{
int *equation = NULL, value;
size_t i, count = 0;
puts("Enter integer: (Enter 'q' to quit)");
while(1 == scanf("%d",&value))
if(!AddArray(&equation, &count,value)) break;
for(i = 0; i < count;i++)
printf("equation[%u] = %d\n",i,equation[i]);
free(equation);
return 0;
}
int AddArray(int **array, size_t *count, int value)
{
int *tmp = realloc(*array,((*count)+1)*(sizeof *tmp));
if(tmp)
{
*array = tmp;
(*array)[(*count)++] = value;
return 1;
}
return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto:
xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/