Hi all,
This is the code that was giving me trouble. It terminates during the first for loop for reasons that I don't understand. Debugging with gdb revealed a segmentation fault.
Code:
#include <stdio.h>
int main() {
int *arr,size,sum=0;
printf("Enter the size of your array: ");
scanf("%i",&size);
for(int i=0;i<size;i++) {
printf("Element %i: ",i+1);
scanf("%i",arr+i);
}
for(int i=0;i<size;i++) {
sum = sum + *(arr+i);
}
printf("The total size is %i",sum);
return 0;
}
I was able to fix the segmentation fault by moving the sum calculation to a separate function. But I'd like to know why the first code block is failing. Does anybody have any insight? Thanks in advance.
Fixed code:
Code:
#include <stdio.h>
int main() {
int *arr,size;
printf("Enter the size of your array: ");
scanf("%i",&size);
for(int i=0;i<size;i++) {
printf("Element %i: ",i+1);
scanf("%i",arr+i);
}
printf("The total size is %i",sum(arr,size));
return 0;
}
int sum(int *pt,int size) {
int sum = 0;
for(int i=0;i<size;i++) {
sum = sum + *(pt+i);
}
return sum;
}