0

I have been trying to write a simple code wherein the array is allocated dynamically. Every time I specify the side of the array as n(suppose 4) and proceed to type the given input, it takes exactly n+1(5 in this case) inputs from me but as the output, it prints n(4) elements.

Here's the main function I wrote:

int main() {
    int *arr, n;
    scanf("%d", &n); //n is the size
    arr = (int *)malloc(n*sizeof(int));
    for(int i=0; i<n; i++) {
        scanf("%d ", &arr[i]);
    }
    for(int i=0 ; i<n; i++) {
        printf("%d ", arr[i]);
    }
}

I've also tried doing the code by initializing i in the first loop as 1, and in that way it takes exactly n inputs but it gives a weird output, something like this:

7953616 1 2 3
Barmar
  • 741,623
  • 53
  • 500
  • 612
slayk
  • 7
  • 5

1 Answers1

0

in those two lines

    scanf("%d ", &arr[i]);
    printf("%d ", arr[i]);

you have %d instead of %d

also you need to use free() from stdlib library as after you finish using the pointer you need to free the memory in order to reuse it again otherwise this will happen

final code

#include <stdio.h>
#include <stdlib.h>
int main() {
 int *arr, n;
 scanf("%d", &n); //n is the size
 arr = (int *)malloc(n*sizeof(int));
 for(int i=0; i<n; i++) 
 scanf("%d", &arr[i]);
 for(int i=0 ; i<n; i++) 
 printf("%d", arr[i]);
 free(arr);
}