Reputation: 11
I have this excercise:
Write a C function RandArr2() that takes as parameters three values:
The function RandArr2() returns an array as follows:
This is my implementation that return a Segmentation faults.
#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;
}
I'm new in C, so you're welcome for every kind of help.
Upvotes: 0
Views: 353
Reputation: 1757
I have fixed some issues related to segmentation fault in your program. I have removed the rand()
function to make things more clear. You can add rand()
wherever you want to add as per your requirements.
The main issue was however, in the for
loop in the main()
you are printing the contents of the returned array. I have fixed it. Please check the test-expression
in the for
loop in main()
for understanding the issue. The index of the array cannot be more than array_size-1
as index for array starts from 0
.
The fixed code is below.
#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;
}
Upvotes: 2