Originally Posted by
shruthi
Is there a way to reduce the number of pointers used in this program using malloc itself.
You would only need two pointers: One which is always pointing to the start of your array and another "helper" pointer which does all the moving around.
Something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *numbers, *temp;
int i;
if ((numbers = malloc(5 * sizeof(*numbers))) == NULL)
{
fprintf(stderr, "Error allocating memory\n");
exit(EXIT_FAILURE);
}
printf("Enter the 5 numbers\n");
for(i = 0, temp = numbers; i < 5; i++, temp++)
scanf("%d", temp);
temp = realloc(numbers, 8 * sizeof(*numbers));
if (temp != NULL)
numbers = temp;
else
{
fprintf(stderr, "Error reallocating memory\n");
free(numbers);
exit(EXIT_FAILURE);
}
printf("Enter 3 more numbers\n");
for(i = 0, temp = numbers + 5; i < 3; i++, temp++)
scanf("%d", temp);
printf("The numbers: ");
for(i = 0, temp = numbers; i < 8; i++, temp++)
printf("%d ", *temp);
putchar('\n');
free(numbers);
return EXIT_SUCCESS;
}
Bye, Andreas