-4
struct Node *addToEmpty(struct Node *last, int data) 
{ 
  // This function is only for empty list 
  if (last != NULL) 
    return last; 

  // Creating a node dynamically. 
  struct Node *temp =  
       (struct Node*)malloc(sizeof(struct Node)); 

  // Assigning the data. 
  temp -> data = data; 
  last = temp; 

  // Creating the link. 
  last -> next = last; 

  return last; 
} 

struct Node *addBegin(struct Node *last, int data) 
{ 
  if (last == NULL) 
      return addToEmpty(last, data); 

  struct Node *temp =  
        (struct Node *)malloc(sizeof(struct Node)); 

  temp -> data = data; 
  temp -> next = last -> next; 
  last -> next = temp; 

  return last; 
} 

i wanna know why "*addToEmpty" is used not "addToEmpty".

what is "*" mean in struct?

I know it's basic question. but I can't find the answer.

I'm gonna be filling well today if you reply to my question

P.S. it's c++ code.

Elvis Dukaj
  • 7,142
  • 12
  • 43
  • 85
  • The return type is `Node*` (Pointer to Node). Try to read it like this: `struct Node* addToEmpty(struct Node *last, int data)` – Shloim Nov 18 '19 at 08:05
  • look at the return values of the functions. You return a pointer to a Nodes, the return type is `Node *`. For me I like it more if it is written like `Node* ` – RoQuOTriX Nov 18 '19 at 08:05
  • 2
    This is way more C than C++ – Fareanor Nov 18 '19 at 08:06
  • https://stackoverflow.com/questions/6990726/correct-way-of-declaring-pointer-variables-in-c-c Attempts to explain why (some) C programmers declare pointers that way. – jrok Nov 18 '19 at 08:22
  • Related : [Use of '&' operator before a function name in C++](https://stackoverflow.com/questions/23776784/). It is the same issue here, just using `*` instead of `&`. They both apply to the return type, not to the function name. – Remy Lebeau Nov 18 '19 at 08:23

2 Answers2

5

This is the A and B of C(++) [Pun intended].

In this function, you are returning a pointer to node struct...

You are asking us to teach you the basics of Pointers. Take a look at https://en.cppreference.com/w/cpp/language/pointer or google "using pointers in C++" and all shall be explained.

Lior
  • 284
  • 1
  • 6
3

Just change the way you read it:

  • struct Node would mean we return a struct of type Node. In c++ the struct keyword is not neccesary.

  • Now the * belongs to the return type, not to the function name. struct Node * is a pointer to a struct of type Node

  • And addToEmpty is the function name.

You could also just wrtie Node* addToEmpty if that's clearer to you. It's just a matter of personal preference here and makes it clearer that addToEmpty returns a Node* (a pointer to a Node)

Lukas-T
  • 11,133
  • 3
  • 20
  • 30