If you want to return a pointer from a function, you need to make sure that it points to valid memory.
Here are two ways you can make sure of that :
1) by allocating memory outside of the function, and passing it as an argument :
int *add(int *psum, int *pa, int *pb) {
*psum = *pa + *pb;
return psum;
}
and you can call it like this :
int a = 10, b = 50;
int sum = 0;
int *psum = 0;
psum = add(&sum, &a, &b);
printf(" sum : %d\n sum via pointer : %d\n", sum, *psum);
note that sum will contain the result of the function, and psum will point to that SAME value. In other words, if after calling the function, we change sum :
sum = 20;
printf(" sum : %d\n sum via pointer : %d\n", sum, *psum);
then psum will also point to 20.
2) by allocating memory inside of the function :
int *add(int *pa, int *pb) {
int *psum = (int*) calloc(1, sizeof(int));
*psum = *pa + *pb;
return psum;
}
The calloc call allocates memory dynamically for the return value. This memory will still be valid after the function returns, which is what we need.
and you can call it like this :
int a = 10, b = 50;
int *psum = 0;
psum = add(&a, &b);
printf(" sum via pointer : %d\n", *psum);
free(psum);
note that psum will point to the result of the addition.
The call to free is ABSOLUTELY needed once we don't need the result any more ... otherwise there is a memory leak.
Main Topics
Browse All Topics





by: Infinity08Posted on 2007-05-26 at 01:53:27ID: 19161422
*a is an int, and so is *b (you are dereferencing the pointers). So, doing this :
*a + *b
has an int as result, NOT a pointer. So, your add function returns an int while it should return an int*.
Now, that's not the only problem in your code :
int *a = 10;
a is an int*, and you assign it a value. That will more than likely generate a runtime error. Here's some corrected code :
int add(int*, int*); /* <--- the function takes two int pointers as argument, and returns the sum as an int */
int main() {
int a = 10, b = 50; /* <--- we make a and b proper ints */
int c = 0; /* <--- this will be the result of the function */
c = add(&a, &b); /* <--- instead of passing the values of a and b, we pass their addresses */
printf("The value is %d\n", c);
return 0; /* <--- usually, 0 indicates correct termination of the program - non-zero values indicate an error */
}
int add(int *pa, int *pb) {
return (*pa + *pb); /* <--- we dereference the pointers to get the actual values, sum them and return the result */
}