我正在嘗試解決 Hacker Rank 上的 C 中的一維陣列問題: 這里
我們必須列印陣列中整數的總和。
我的代碼:
#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 Code 中正常運行。
- 我給出的自定義輸入(即自定義測驗用例)編譯成功(使用 Hacker Rank 的“針對自定義輸入進行測驗”功能)。
- 但是只有一些選擇的測驗用例會給出這個錯誤。
請指出我的代碼中可能導致此問題的錯誤。
uj5u.com熱心網友回復:
在動態初始化記憶體空間之前指定陣列的大小。如何在輸入陣列大小之前初始化空間?
當您動態分配記憶體時,您必須指定強制轉換型別。
這里: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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/417892.html
標籤:
