today i started learning C, and i got stucked in function pointers. This is my code:
main.c:
#include <stdio.h>
int sumOfElements(int *arr, int arr_elements);
int main()
{
int (*ptr)(int,int) = NULL;
ptr = sumOfElements;
int a[] = {128, 64, 32, 16, 8, 4, 2, 1};
printf("Total of price is: %d", ptr(a, 8));
}
int sumOfElements(int *arr, int arr_elements)
{
int k =0;
int total;
for(;k < arr_elements;k++)
{
total += arr[k];
}
return total;
}
What i'm trying to do is access the elements of the array in the sumOfElements
functions. When i call it normally, then everything goes smooth. When i try to use the function pointer
, then the compiler throw me some warning before, and then the Segmentation Fault
error:
main.c:17:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
main.c:19:41: warning: passing argument 1 of ‘ptr’ makes integer from pointer without a cast [-Wint-conversion]
main.c:19:41: note: expected ‘int’ but argument is of type ‘int *’
Segmentation fault (core dumped)
Since i'm still learning it, i'm unsure about touching the code, because, like i said before, it works without the function pointer
. Now, the error main.c:17:9: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
, i didn't really understand it, because they're both int
. So, if you could explain that too, it would save me a lot of time. So, why does it only throw Segmentation Fault (core dumped)
when i use the funptr
? All i know is that the Segmentation error is when we try to access memory that is only read-only
or it's out-of-bound