Question

int* sum(int *mypt,int len){
int i;
int mysum = 0; 
for(i=0;i<len;i++)
  mysum += mysum;   
  return &mysum; // I cannot do this since the function frame goes away after the call.
}

int main()
{

  int *pt = (int*) malloc(3*sizeof(int));   
  pt[0] = 0;
  pt[1] = 1;
  pt[2] = 2;

  int *s = sum(pt,3);
  printf("%d\n",*s);    
  return 0;
 }

I would like to return a pointer to the mysum. I cannot do int static sum = 0 because it is fixed. I cannot use int const sum = 0 because it gives an error ""readonly"". Is there a solution to this ?

Was it helpful?

Solution 2

Yes, use malloc to place the integer in heap memory and obtain a pointer. You can then return this pointer from the function:

int* sum(int *mypt, int len) {
    int i;
    int* mysum = malloc(sizeof(int));

    //make sure you dereference (*) when you wish to work with the value.
    *mysum = 0;

    for(i=0; i<len; i++) *mysum += *mysum; 

    return mysum; 
}

Aside, it looks like a lot of your code is broken. This only solves how to return the pointer!

OTHER TIPS

why do you need to return a pointer from sum() you can just return the answer by value. If you must return a pointer, than you will need to malloc() the memory inside of sum() and the caller of sum will have to free() the answer, but that is not very efficient.

int sum(int mypt, len)
{
int i;
int mysum = 0; 
for(i=0;i<len;i++)
  mysum += mysum;   
  return mysum; // return the answer by value.
}

And change main() as below:

int main()
{

  int *pt = (int*) malloc(3*sizeof(int));   
  pt[0] = 0;
  pt[1] = 1;
  pt[2] = 2;

  int s = sum(pt,3);
  printf("%d\n",s);    
  return 0;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top