c - 在 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));
}
}
解决方案
您的程序不完整,但至少有以下几行:
q->k = &k;
q->th = &th;
将结构中的字段设置为指向堆栈上的值的指针 -createReverseCircle
返回后,取消引用这些指针会导致未定义的行为。
推荐阅读
- java - Gradle 构建失败,出现错误 checkstyleMain FAILED
- javascript - 如何在 React 中过滤来自 API 和 setState 的 JSON 数据
- c++ - 这个拓扑排序算法的复杂度是 O(P+D),其中 P 是项目,D 是依赖项?
- javascript - 如何根据对象中的属性合并对象数组中的对象
- firefox - 在 Visual Studio Code 中调试时 Firefox 未打开
- mysql - 环回应用程序功能错误
- java - 如何传入一个类来创建一个类数组?
- javascript - 如何使用 Javascript 中的正则表达式验证我的密码 - 附加的代码每次都评估为 false
- c++ - 提升进程间向量比 std::vector 慢
- javascript - fetch 返回 ReadableStream 作为错误主体。如何获取该流的内容?