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

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!

其他提示

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;
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top