简体   繁体   中英

Using A Struct Object in a Function

I have written a piece of code for queue.

#include <iostream>
using namespace std;

struct q
        {
            int items[10];
            int front,rear;
        } queue;

void Addqueue(struct q *queue, int item)
{
    if (queue->rear==9)
        cout << "Queue is Full.";
    else
        queue->items[++queue->rear]=item;
}


int main()
{
    queue.front=queue.rear=-1;
    Addqueue(q *queue,5);
    return 0;
}

As you can see I have used struct object for it. In Addqueue Function, first element is (struct q *queue), I want to know what should I write instead of it, while I'm caling this function in main function, for example I tested Addqueue(q *queue,5) and Addqueue(queue,5) and Addqueue(*queue,5) and Addqueue(struct q *queue,5), but none of them works and I will get an error for this line. so what should I do? what is wrong?

The correct syntax is Addqueue(&queue, 5) . Addqueue accepts a pointer to a struct q , so you need to get queue 's address with the address-of operator& to pass in.

That said, you should absolutely use std::queue<int> instead of your own home-grown queue.

#include <iostream>
using namespace std;

struct q
{
    int items[10];
    int front,rear;
} queue;

void Addqueue(q *queue, int item)
{
    if (queue->rear==9)
        cout << "Queue is Full.";
    else
        queue->items[++queue->rear]=item;
}


int main()
{
    queue.front=queue.rear=-1;
    Addqueue(&queue, 5);
    return 0;
}

That's correct way.

You created pointer to struct q , but it has not allocated memory. And local name of pointer q *queue override your object queue .

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