For some reason, my function is only returning the first element in my array and I cannot figure out why the rest of the array goes out of scope. The function takes two integer arrays, adds their respective elements, and puts the sum into a third array which is returned.
Here is my code:
#include <stdio.h>
/* count digits, white space, others */
int *sumarrays(int arr1[], size_t arr1len, int arr2[], size_t arr2len);
void main() {
int arr1[10];
size_t arr1len = 10;
int arr2[10] = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
size_t arr2len = 10;
int i;
int *x;
arr1[0] = 2;
arr1[1] = 3;
arr1[2] = 2;
arr1[3] = 2;
arr1[4] = 2;
arr1[5] = 2;
arr1[6] = 3;
arr1[7] = 2;
arr1[8] = 2;
arr1[9] = 2;
//printf("%d\t%d\t%d\n", arr1, *arr1, *(arr1 + 1));
x = sumarrays(arr1, arr1len, arr2, arr2len);
for (i = 0; i < 10; i++) {
printf("Array1: %d\tArray 2: %d\tX = %d\n", arr1[i], arr2[i], x[i]);
}
//return 0;
}
int *sumarrays(int arr1[], size_t arr1len, int arr2[], size_t arr2len) {
int i;
int total[10];
for (i = 0; i < 10; i++) {
total[i] = *(arr1 + i) + *(arr2 + i);
}
for (i = 0; i < 10; i++) {
printf("%d\t", total[i]);
}
printf("\n");
return total;
}
Here is the output:
4 5 4 4 4 4 5 4 4 4
Array1: 2 Array 2: 2 X = 4
Array1: 3 Array 2: 2 X = 1974388256
Array1: 2 Array 2: 2 X = -161927102
Array1: 2 Array 2: 2 X = 2686628
Array1: 2 Array 2: 2 X = 8670801
Array1: 2 Array 2: 2 X = 0
Array1: 3 Array 2: 2 X = 27
Array1: 2 Array 2: 2 X = 2686540
Array1: 2 Array 2: 2 X = 4
Array1: 2 Array 2: 2 X = 2686916
The first line is the sum array elements from within the function. The remainder is what happens in the main().
What am I missing?
*edit* ANSWERED
Thank you everyone for the help! I actually learned C and C++ a while ago but have recently started to go back and fine tune my knowledge. Really appreciate all the help.
The main answers were
1) Statically allocate memory (using the static keyword)
2) Dynamically allocate memory (using malloc())
3) Make the variable global
4) Pass the result total() as an argument to the function so it doesn't go out of scope.
totallives, and its existence (or lack thereof) once your function returns.