【问题标题】:Issue passing struct through method/function in c通过 c 中的方法/函数传递结构的问题
【发布时间】:2020-04-15 12:06:26
【问题描述】:

我在使用以下方法时遇到问题。它应该将mq.queue[qCounter].id 的值更改为ident 中的值,它会执行此操作,但在方法完成后该值不会保留在外部。它似乎只在方法中发生变化。我尝试取消引用属性mq,但没有编译错误,但程序在到达该方法时停止运行。有什么想法可以修复它/使用方法/函数实现相同的目标吗?

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++;
    }
}

以下是上面使用 aka "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;

【问题讨论】:

  • MsgQs_t mqis pass by value 使它作为一个指针来改变调用函数

标签: c function methods attributes dereference


【解决方案1】:

在函数createQ 中,参数MsgQs_t mq 用作pass-by-value,因此调用者组件在mq 中编辑时不会有任何更改

将代码更改为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++;
            }
        }

调用函数时发送地址如下,

createQ(&mq, indent_value);

【讨论】:

  • 很抱歉,但我对 C 语言比较陌生。我如何更改你写“^^^^^^ Here”的参数以使其通过指针,因为我想添加 *让它通过指针
  • geeksforgeeks.org/…此获取更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 2022-12-04
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多