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.

1
  • 1
    You never seem to modify a... Commented Jan 8, 2013 at 0:05

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.