2

Here is an array implementation of stack I'm trying to accomplish.

 #include<stdio.h>
 #include<stdlib.h>


#define MAX 5


typedef struct
{
    int arr[MAX];
    int top;
}STACK;



//#typedef struct stack STACK;



//---------------------- PUSH  and POP ----------------
//push----
void push(STACK &s, int num)
{
    if (s.top == MAX-1)
    {
        printf("\n\nstack full\n");
        return;
    }
    else
    {
        s.top = s.top + 1;
        s.arr[s.top] = num;
    }
    return;
}
//pop----
int pop(STACK &s)
{
    int num;
    if(s.top == -1)
    {
        printf("\n\nStack is empty\n");
        return s.top;
    }
    else
    {
        num = s.arr[s.top];
        s.top = s.top -1;

    }
    return num;

}

// ---main
int main()
{

    STACK s;

    int popped;
    s.top = -1;

    push(s, 1);
    printf("%d \n",s.top);
    push(s, 2);
    printf("%d \n",s.top);
    push(s, 3);
    printf("%d \n",s.top);


    popped = pop(s);
    popped = pop(s);
    popped = pop(s);
    popped = pop(s);

    printf("%d \n",popped);
    return 0;
}

When in int main(), if I do

push(&s,VALUE)

I'm passing by reference, and I can use

void push(STACK *s, int VALUE)

to dereference it. The program works fine.

However, when I do call-by-reference like:

push(s, VALUE)

and in the call,

void push(STACK &s, int value)

I get error saying "too many arguments to function call, expected 1, have 2"

What am I doing wrong? Isn't the call-by-reference correct?

Raaj
  • 1,180
  • 4
  • 18
  • 36
  • 5
    AFAIK, there is no call-by-reference in c. While passing function parameters, c uses pass-by-value. _pass-by-reference_ is simulated by passing a pointer. – Sourav Ghosh May 26 '15 at 19:15
  • 3
    That is c++ or it's being compiled by the wrong compiler, because `&` in function parameters is fortunately not valid in c. – Iharob Al Asimi May 26 '15 at 19:24
  • That's something I learnt ONLY now. So this would be perfectly valid in C++ ? – Raaj May 26 '15 at 19:25

2 Answers2

0

Passing by reference in C, is the same thing of using pointers, so your code should be like this:

int main(void)
{
    int num;
    num = 10;
    incrementa_num(&num); //Use & when you "call-by-reference" in C
    printf("Num: %d\n", num);
    getch();
    return 0;
}

void incrementa_num(int *num) //And use "*" in the subroutine
{
    *num = *num + 1; 
}

If you wanna do the same in C++, you should put the "&" when you declare the variable in the subroutine.

Gabriel
  • 763
  • 1
  • 10
  • 28
0

The concept of pass-by-reference is in C++.

In C, it is interchangeably used as pass-by-pointer. However, it can't be used the way (syntax) it is used in C++.

You can also refer to earlier discussion on the similar topic in SO.

Community
  • 1
  • 1
Pawan
  • 1,537
  • 1
  • 15
  • 19