简体   繁体   中英

Using pointer to save the data that's being returned from the function in c

  1. When we wanna return one particular type of data, we need to declare a global variable first right? and assign this variable to the value thats being returned by the funtion?

  2. Also for int primitive data type, we cannot use malloc to reserve memory block?

Sincerely, headful of doubts.

#include <math.h> 
#include <stdio.h> 

int *sum(); 
int main() 
{ 
    int *num; 
    num = sum(); 
    printf("\nSum of two given values = %d", *num); 
    return 0; 
} 

int *sum() 
{ 
    int a = 50, b = 80;
    int *sum = NULL; 
    printf("%d %d",a,b);
    *sum = a+b; 
    return sum; 
} 

I wanna using pointers to save the data thats being returned by the function. is it possible? I know it's possible for linked list structures. But I'm not sure about integers and other primitive data types.

Starting with your second question, you can use malloc to allocate memory of any size for any type of variable. Yes, you can use malloc to allocate ints and other primitive types on the heap.

int i_am_a_stack_variable = 1;
int * i_am_a_pointer_to_heap_memory = malloc(sizeof(int));

For your first question, I think you are mis-understanding how return variables work. Typically, the use of global variables should be avoided. They certainly aren't needed to return values from functions. The return value of a function is copied from the function's stack frame back to the calling stack frame wherever it is assigned. Note that it is COPIED back. Whether it is a primitive type or a pointer (which is really just another type of primitive). Your code could be written just not using pointers at all. Also, note that your code was not using a global variable at all even though you mentioned global variables.

#include <math.h> 
#include <stdio.h> 

int sum(); 
int main() 
{ 
    int num; 
    num = sum(); 
    printf("\nSum of two given values = %d", num); 
    return 0; 
} 

int sum() 
{ 
    int a = 50, b = 80;
    int sum = 0; 
    printf("%d %d",a,b);
    sum = a+b; 
    return sum; 
} 

Does this make sense?

This should work

#include <math.h> 
#include <stdio.h> 

int *sum(); 
int main() 
{ 
    int *num; 
    num = sum(); 
    printf("\nSum of two given values = %d", *num); 
    free(num);
    return 0; 
} 

int *sum() 
{ 
    int a = 50, b = 80;
    int *sum = malloc(sizeof(int)); 
    printf("%d %d",a,b);
    *sum = a+b; 
    return sum; 
}

You need to allocate memory for the pointer. In your case you need memory for one Integer. When you say int* sum =NULL your pointer has no Adress. You can't access a null pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM