简体   繁体   English

问题通过 c 中的方法/函数传递结构

[英]Issue passing struct through method/function in c

I am having issues with the following method.我在使用以下方法时遇到问题。 It supposed to change the value of mq.queue[qCounter].id to that found in ident and it does this but the value is not retained outside after the method is done.它应该将mq.queue[qCounter].id的值更改为在ident中找到的值, mq.queue[qCounter].id ,但在方法完成后该值不会保留在外面。 It only seems to change while in the method.它似乎只在方法中发生变化。 I tried de-referencing the attribute mq but and there were no compilation errors but the program stopped running whenever it got to the method.我尝试取消引用属性mq但是没有编译错误但是程序在到达该方法时停止运行。 Any ideas how I can fix it/ achieve the same thing using a method/function?任何想法如何修复它/使用方法/函数实现同样的事情?

void createQ(MsgQs_t mq, int ident){
    int taken=0;
    for(int i=0;i<3;i++){
        if(mq.queue[i].id==ident){
            printf("That Queue Id is already taken\n");
            taken=1;
        }
    }
    if(taken==0){
    mq.queue[qCounter].id=ident;
    printf("THE INNER ID IS %d and the qCounter is %d\n", mq.queue[qCounter].id, qCounter);
    qCounter++;
    }
}

The following is the struct im using aka "MsgQs mq" above:以下是上面使用又名“MsgQs mq”的结构体:

typedef struct MessQ {//A single message queue
    char message[MQS][MLN];
    int id;
}MessQ_t;

typedef struct MsgQs {//An array of message queues
    MessQ_t queue[MQA];
}MsgQs_t;

In function createQ argument MsgQs_t mq used as pass-by-value and hence caller component will not have any changes upon editing in mq在函数createQ参数MsgQs_t mq用作pass-by-value ,因此调用者组件在mq编辑时不会有任何更改

Change code to pass-by-reference something like,将代码更改为pass-by-reference例如,

 void createQ(MsgQs_t *mq, int ident){
//                    ^^^^^^ Here
        int taken=0;
        for(int i=0;i<3;i++){
            if(mq->queue[i].id==ident){
  //           ^^^^^^ Here change dot(.) to this (->) for access
                    printf("That Queue Id is already taken\n");
                    taken=1;
                }
            }
            if(taken==0){
            mq->queue[qCounter].id=ident;
            printf("THE INNER ID IS %d and the qCounter is %d\n", mq->queue[qCounter].id, qCounter);
            qCounter++;
            }
        }

While calling the function send the address as follows,在调用函数时发送地址如下,

createQ(&mq, indent_value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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