Adobe Interview Question
Country: India
Interview Type: In-Person
* realloc example: rememb-o-matic */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int input,n =0;
int count=0;
int * numbers = NULL;
int * more_numbers;
while(1)
{
do {
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input);
count++;
more_numbers = (int*) realloc (numbers, count * sizeof(int));
if (more_numbers!=NULL) {
numbers=more_numbers;
numbers[count-1]=input;
}
else {
free (numbers);
puts ("Error (re)allocating memory");
exit (1);
}
} while (input!=0);
printf ("Numbers entered: ");
while(n<count)printf ("%d ",numbers[n]);
}
return 0;
}
If I am getting the problem correctly, then it means whenever 500 appears we have to print all the elements before it.
Hence we can keep on storing numbers in a file and whenever a 500 comes, we should print all the content of file on stdout and make the file empty.
how do you know that file contents are allocated contiguously , a simple text editor could use a large buffer or a linked list as a Data structure?
Hello Anonymous. Thank you very much for posting your code. I have been stuck for a couple of weeks on Ex7.1, Pg 330 of Beginning C, Ivor Horton. I have adapted your code to enter an unspecified number of float values, and then print them out with the average as well. You have saved me much time.
Best regards.
/*realloc_for_averaging_value_of_floats_fri14Sept2012_16:30 */
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
int main (int argc, char ** argv[])
{
float input =0;
int count=0 ,n =0;
float * numbers = NULL;
float * more_numbers;
float sum = 0.0;
while(TRUE)
{
do {
printf ("Enter an floating point value (0 to end): ");
scanf ("%f", &input);
count++;
more_numbers = (float*) realloc (numbers, count * sizeof(float));
if (more_numbers!=NULL)
{
numbers=more_numbers;
numbers[count-1]=input;
}
else
{
free (numbers);
puts ("Error (re)allocating memory");
exit (TRUE);
}
} while (input!=0);
printf("Numbers entered: ");
while(n<count){printf("%f ",numbers[n]); /* n is always less than count.*/
n++;}
/*need n++ otherwise loops forever*/
n=0;
while(n<count)
{
sum += numbers[n]; /*Add numbers together*/
n++;
};
printf("\n Average of floats = %f \n",sum/(count-1));/* Divide sum / count = average.*/
}
return 0;
}
/* Success Fri Sept 14 13:29 . That was hard work.*/
/* Always looks simple when working.*/
/* Next step is to use a function to work out the average.*/
/*Anonymous on July 04, 2012*/
1. Allocate some memory and keep pushing the numbers as it comes.
- tp July 02, 20122. If u run out of memory, realloc
3. when u get 500, return the pointer.
Am I missing something?