我正在尝试解决Hacker Rank上的C中的1D数组问题:此处
我们必须打印数组中整数的和。
我的代码:
#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;
}
但是编译器为某些选定的测试用例提供了错误编译器消息(错误(:
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
一些观察:
- 此程序在VS代码中正常运行
- 我给出的自定义输入(即自定义测试用例(成功编译(使用Hacker Rank的"针对自定义输入的测试"功能(
- 但是,只有一些选定的测试用例才会出现这种错误
请指出导致此问题的代码中可能存在的错误。
在动态初始化内存空间之前指定数组的大小。在输入数组大小之前,如何初始化空间?
在动态分配内存时,必须指定强制类型。
此处:a=(cast_type*(malloc(byt_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: %dn", sum);
free(a);
return 0;
}