0

I'm trying to use realloc to add an element to an array after inputting characters. Here is my code:

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

   int main(void)
   {
      int i, j, k;
      int a = 1;
      int* array = (int*) malloc(sizeof(int) * a);
      int* temp;
      for(i = 0;;i++)
      {
          scanf("%d", &j);
          temp = realloc(array, (a + 1) * sizeof(int));
          temp[i] = j;
          if(getchar())
            break;
      }
      for(k=0; k <= a; k++)
      {
          printf("%d", temp[k]);
      }
   }

When I run this little program, and if I enter for exemple : 2 3 4 it displays me: 20; I know that memory hasn't been allocated properly, but I can't figure out the issue. Thanks in advance.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335

1 Answers1

0

Firstly:

    int* array = (int*) malloc(sizeof(int) * a);
    int* temp = array;

and

    temp = realloc(temp, (a + 1) * sizeof(int));

because after call 'realloc' pointer passed as first argument may becomes invalid.

And of course 'realloc' called with second parameter equal 2 always.

By the way 'scanf' stops read your input string after first non-digit character. Read documentation for correctly usage functions. For example about scanf() or realloc().

declonter
  • 321
  • 1
  • 7
  • I fix only incorrect using of allocaters. Your code contain several other errors for example: incorrect using 'scanf', first element in array is undefined, but you try to out it in last loop, and so on. – declonter Jan 08 '13 at 00:44