[comp.lang.c] redeclaring in middle of body

muttiah@stable.ecn.purdue.edu (Ranjan S Muttiah) (02/09/91)

In C is it possible for me to do the following:
	main()
	{
	int array[10];

	body of program;

	redimension array. Ex., int array[50];

	body of program cont'd.
	}

So far, I have got syntax errors when I do that.

Thanks.  Please email if possible.

darcy@druid.uucp (D'Arcy J.M. Cain) (02/10/91)

In article <1991Feb8.180443.22477@noose.ecn.purdue.edu> Ranjan S Muttiah writes:
>In C is it possible for me to do the following:
>	main()
>	{
>	int array[10];
>	body of program;
>	redimension array. Ex., int array[50];
>	body of program cont'd.
>	}
>So far, I have got syntax errors when I do that.

You can do:

int function(void)
{
  int array[10];
  ...
  {
    int array[50];
    ...
  }
  ...
}

However I suspect this is not what you want since the second declaration is
totally unrelated to the first.  It is a different variable.  If you just
want to have a larger array why not simply declare it larger in the first
place?  If there was some way to do what you suggest the space would have
to be allocated on the stack at the start anyway so you don't save anything
by putting it off.

Of course what you probably *really* want is malloc and realloc:

int function(size_t init_size)
{
  int *array = malloc(init_size);
  size_t new_size = init_size;
  ... /* new_size gets changed somewhere here */
  array = realloc(new_size);
  ...
}

Hope this answers the question you didn't ask.  :-)

-- 
D'Arcy J.M. Cain (darcy@druid)     |
D'Arcy Cain Consulting             |   There's no government
West Hill, Ontario, Canada         |   like no government!
+1 416 281 6094                    |