首页 > 解决方案 > 在 C 中赋值后结构不保持值。尝试打印时不显示任何值

问题描述

我正在尝试为某些结构分配值,以便稍后在我的代码中再次使用这些值,但我似乎无法让这些结构保持它们的值。打印 createReverseCircle() 函数内的值可以工作,但函数外的任何内容都不能。我是否错误地分配了值?

struct queue
{
    struct soldier *front;
    struct soldier *back;
    char groundName[50];
    int *k;
    int *th;
};

int main()
{

    struct queue *theQueues = (struct queue *)malloc(sizeof(struct queue) * N);
    for (int i = 0; i < N; i++)
    {
        init(&theQueues[i]);
    }

    createReverseCircle(&theQueues[0], 10, "Test Ground", 3, 2);

    //These print statements print nothing or give me an error
    printf("%s", theQueues[0].groundName); 
    printf("%d", theQueues[0].k);


void createReverseCircle(struct queue *q, int numOfSoldiers, char groundName[50], int k, int th)
{
    strcpy(q->groundName, groundName);
    q->k = &k;
    q->th = &th;

    for (int j = numOfSoldiers; j >= 1; j--)
    {
        enqueue(q, createSolider(j));
    }
}

标签: c

解决方案


您的程序不完整,但至少有以下几行:

q->k = &k;
q->th = &th;

将结构中的字段设置为指向堆栈上的值的指针 -createReverseCircle返回后,取消引用这些指针会导致未定义的行为。


推荐阅读