I have a question about return an array from a function in C, I do not know why it keeps giving the result as a code dumped. Please help, I really really thank you! I set up an int list3[size3] but it seems like I have to return with a format of an array as int*list3. So I set up another array as list4[size3] to copy list3 into list4. But I am not sure it is a reason it cause code dumped. If it is, please help me with the advice to solve the problem. Thank you so much again!.
#include<stdio.h>
int* merged(int[], int[], int, int);
void sort(int[], int);
int main() {
int size1;
printf("Enter list1: ");
scanf("%d", &size1);
int list1[size1];
for (int i = 0; i < size1; i++) {
scanf("%d", &list1[i]);
}
int size2;
printf("Enter list2: ");
scanf("%d", &size2);
int list2[size2];
for (int i = 0; i < size2; i++) {
scanf("%d", &list2[i]);
}
int* list3 = merged(list1, list2, size1, size2);
printf("The merged list is: ");
int size3 = size1 + size2;
for (int i = 0; i < size3; i++) {
printf("%d ", list3[i]);
}
printf("\n");
}
int* merged(int list1[], int list2[], int size1, int size2) {
int list3[size1 + size2];
for (int i = 0; i < size1; i++) {
list3[i] = list1[i];
}
int count = size1;
for (int i = 0; i < size2; i++) {
list3[count] = list2[i];
count++;
}
int size3 = size1 + size2;
sort(list3, size3);
int* list4;
for (int i = 0; i < size3; i++) {
list4[i] = list3[i];
}
return list3;
}
void sort(int list3[], int size3) {
for (int i = 0; i < size3; i++) {
int min = list3[i];
int min_index = i;
for (int j = i + 1; j < size3; j++) {
if (list3[j] < min) {
min = list3[j];
min_index = j;
}
}
if (min_index != i) {
list3[min_index] = list3[i];
list3[i] = min;
}
}
}
list3). You cannot use a pointer variable which has not been initialized to point to some object (list4). If you want a function to return an array, you basically have two options: dynamically allocate the array withmallocor create the array in the caller and supply it as an additional parameter.