[英]C exercise with malloc and realloc in a function
我有這個練習:
編寫一個 C function RandArr2() ,其參數為三個值:
function RandArr2() 返回一個數組,如下所示:
這是我返回分段錯誤的實現。
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int * RandArr2(int * A, int n, int n1) {
int i;
if (n == n1) {
for (i = 0; i < n; i++) {
A[i] = rand();
}
return A;
} else if (n < n1) {
//reallocs the array A, creating a new array of integers A’ of size n’
A1 = (int * ) realloc(A, n1 * sizeof(int));
return A1;
} else {
/*reallocs the array A, creting a new array of integers A’ of size n’; it also fills all the
positions of A’ between n and n’ with random integers between -10 and 10 */
A1 = (int * ) realloc(A, n1 * sizeof(int));
for (i = n; i < n1; i++) {
A1[i] = -10 + rand() % (-10 - 10 + 1);
}
return A1;
}
}
int main() {
int n, n1;
int * A;
int i;
printf("insert two integer:");
scanf("%d, %d", & n, & n1);
A = (int * ) malloc(n * sizeof(int)); //inizializzo l'array
if (A != NULL) {
A = RandArr2(A, n, n1);
for (i = 0; i <= n; i++) {
printf("\n Elemento del vettore: %d", A[i]);
}
free(A);
} else {
printf("Error!");
exit(0);
}
return 0;
}
我是 C 的新手,歡迎您提供各種幫助。
我已經修復了您程序中與分段錯誤相關的一些問題。 我刪除了rand()
function 以使事情更清楚。 您可以根據需要添加rand()
任何想要添加的位置。
然而,主要問題是,在main()
的for
循環中,您正在打印返回數組的內容。 我已經修好了。 請檢查main()
中for
循環中的test-expression
以了解問題。 數組的索引不能超過array_size-1
,因為數組的索引從0
開始。
固定代碼如下。
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int* RandArr2(int* A, int n, int n1) {
int i;
int* A1 = NULL;
if (n == n1) {
for (i = 0; i < n; i++) {
A[i] = 0xDEAD;
}
return A;
}
else if (n > n1) {
//reallocs the array A, creating a new array of integers A’ of size n’
A1 = (int*)realloc(A, n1 * sizeof(int));
return A1;
}
else {
/*reallocs the array A, creting a new array of integers A’ of size n’; it also fills all the
positions of A’ between n and n’ with random integers between -10 and 10 */
A1 = (int*)realloc(A, n1 * sizeof(int));
for (i = 0; i < n; i++) {
A[i] = 0xDEAD;
}
for (i = n; i < n1; i++) {
A1[i] = 0xBEAD;
}
return A1;
}
}
#define _CRT_SECURE_NO_WARNINGS
int main() {
int n, n1;
int* A;
int i;
printf("insert two integer:");
scanf_s("%d, %d", &n, &n1);
A = (int*)malloc(n * sizeof(int)); //inizializzo l'array
if (A != NULL) {
A = RandArr2(A, n, n1);
for (i = 0; i < ((n > n1) ? n1 : n); i++) {
printf("\n Elemento del vettore: 0x%x", A[i]);
}
free(A);
}
else {
printf("Error!");
exit(0);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.