Home > Net >  is there a way we can make functions that return pointers in C?
is there a way we can make functions that return pointers in C?

Time:05-18

I mean, can we make functions return pointer like in this code:

#include <stdio.h>      
int* sum(int* ptr_1, int* ptr_2){
    return (*ptr_1   *ptr_2);   
}       
int main() {
    int x=0, y=0;
    scanf("%d %d", &x, &y);
    int *ptr_x = &x;
    int* ptr_y = &y;
    printf("%d", *sum(ptr_x, ptr_y));
    return 0;
}   

This code takes 2 int numbers and prints sum of them using pointers. It didn't work on ssh but I wanted to ask anyway.

CodePudding user response:

Yes, functions can return pointers.

Your problem is that the expression *ptr_1 *ptr_2 yields a value of type int, not int * (each of *ptr_1 and *ptr_2 are ints, so adding them together gives you an int value).

Whatever that integer value is, it's likely not a valid pointer (it's not the address of an object during that object's lifetime), and the behavior on dereferencing an invalid pointer is undefined. Your code may crash, you may get nonsensical output, something else may happen.

CodePudding user response:

Yes, you can return a pointer, but in this specific case, you do not need to, your sum should simply return an int, not a pointer to int:

 int sum(int* ptr_1, int* ptr_2){
    return (*ptr_1   *ptr_2);   
 }

CodePudding user response:

That code is buggy. It returns the sum of two ints as a pointer which doesn't make sense.

You can return pointers, but they should also point at something (or NULL). Dereferencing the pointer returned by sum (as you do in the printf line) will almost certainly cause undefined behavior.

A contrived but working version of your program:

#include <stdio.h>

int *sum(int *ptr_1, int *ptr_2) {
    // `static` makes `result` stored between calls so it isn't destroyed
    // when the function returns:
    static int result;
    result = *ptr_1   *ptr_2;
    return &result;           // return a pointer pointing at result
}

int main() {
    int x, y;
    if(scanf("%d %d", &x, &y) != 2) return 1;

    int *ptr_x = &x;
    int *ptr_y = &y;
    
    printf("%d", *sum(ptr_x, ptr_y));
}
  • Related