Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
struct Vec;
/* Allows us to write `Vec` instead of `struct Vec`. */

struct Vec {
  int *data;
  size_t length;
  size_t capacity;
};
typedef struct Vec Vec;

Vec *vec_new() {
  Vec *nstr = malloc(sizeof(struct Vec)); // new_struct = nstr
  if (nstr != NULL) {
    nstr->data = malloc(sizeof(int));
    if (nstr->data == NULL) {
      free(nstr);
      return false;
    }
    nstr->length = 0;
    nstr->capacity = 1;
  } else {
    free(nstr);
  }
  return nstr;
}

Vec *xs = vec_new();


What I have tried:

this function Vec *vec_new() returns a struct pointer...why we need to return struct pointer and not just normal struct?

--
please try to explain it to me in simple way .. i m beginner cs student :)
Posted
Updated 25-Jun-21 4:48am

Because C and C++ pass all parameters and return values by value, not by reference.
So if you returned the struct you allocated, what the calling function would get is not the actual item, but a copy:
C
typedef struct MyStruct
   {
   int x;
   int y;
   } MS;
   
   MS* pMS;
MS GetOne(int x, int y)
   {
   MS* p = (MS*) malloc(sizeof(MS));
   p->x = x;
   p->y = y;
   pMS = p;
   return *p;
   }      
int main()
   {
   MS p = GetOne(10, 20);
   pMS->x++;
   printf("%u,%u\n", p.x, p.y);
   printf("%u,%u\n", pMS->x, pMS->y);
   return 0;
   }
gives you:
10,20
11,20
 
Share this answer
 
v2
struct are usually passed and returned using pointers because it is more efficient. Passing (and returning) a struct by value copies all its fields. Passing it by pointer just copies the pointer value.
Moreover, in your case, the called function dynamically allocates memory, hence it has to pass the address (i.e. the pointer) of the allocated memory to the caller in order to allow the caller itself to release it (via free) when appropriate, in order to avoid memory leaks.
 
Share this answer
 
v2
Comments
KarstenK 25-Jun-21 11:24am    
totally agree, a source of nasty bugs :-/
Southmountain 25-Jun-21 13:57pm    
clear explanation as in the textbook!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900