How to assign a integer to a pointer in c?

  • A+

The task is to create a function

 int* pairSumSearch(int* data, int numEls, int pairSum) 

that searches within the first numEls of a list if ints 'data', to find two adjacent integers that sum to 'pairSum' and return a pointer to the position of the first of the two integers. If there are not two ints that sum to pairsum then the function should return a null pointer. I think i have all the code right except for the pointers part.

int* pairSumSearch(int* data, int numEls, int pairSum)  {     int* point = NULL;     int checker = data[0];     for (int i = 1; i < numEls-1; i++) {         if (checker + data[i] == pairSum) {             *point = i-1;             break;         } else {             checker = data[i];         }     }     return point; } 

Test case is

int main(void) {     int data[] = {1, 2, 3, 4, 5, 6, 7, 10, 9, 10};      int* p = pairSumSearch(data, 10, 19);     if (p != NULL) {         printf("Found at position %zd/n", p - data);     }     else {         puts("Not found");     } } 

but i just get seg faults where instead it should return

Found at position 8 


I think

*point = i-1; 

Should be

point = &data[i-1]; 

Without the starting *.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: