I am trying to solve the 1D Arrays in C problem on Hacker Rank: here
We have to print the sum of the integers in the array.
My code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n;
int sum = 0;
int *a = malloc(n * sizeof(int));
scanf("%d", &n);
getchar();
for (int i = 0; i < n; i++)
{
scanf("%d ", &a[i]);
sum += a[i];
}
printf("%d", sum);
free(a);
return 0;
}
But the compiler gives error for some select test cases. The compiler message (error):
Compiler Message:
Abort Called
Error (stderr):
1.corrupted size vs. prev_size
2.Reading symbols from Solution...done.
3.[New LWP 129788]
4.[Thread debugging using libthread_db enabled]
5.Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
6.Core was generated by `./Solution'.
7.Program terminated with signal SIGABRT, Aborted.
8.#0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
Some observations:
Kindly point out the possible error in my code which is causing this problem.
Specify the size of an array before initializing the memory space dynamically. How can you initialize the space before entering the size of an array?
And you have to specify cast type when you allocate the memory dynamically.
here: a = (cast_type *) malloc (byte_size);
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
int sum=0;
printf("Enter size of the array:\n");
scanf("%d", &n);
int *a = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
scanf(" %d", &a[i]);
}
for (int i = 0; i < n; i++) {
sum += a[i];
}
printf("Sum of array elements is: %d\n", sum);
free(a);
return 0;
}