1
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 ?

2 Answers 2

6

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;
 }
Sign up to request clarification or add additional context in comments.

Comments

3

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!

4 Comments

Be sure to check the value of mysum after calling malloc to ensure it's not NULL!
while (!(mysum = malloc(sizeof(int))) {} ;) (This is a joke)
You can use mypt[i] instead of *(mypt + i). Array access is just pointer addition under the hood, as you have found out!
Also you can use len to track the length of remaining elements to process: while (--len >= 0) *mysum += mypt[len];. Then you don't need to introduce a new i. Matter of taste perhaps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.