gpt4 book ai didi

c - 函数调用后变量值发生变化,未被使用

转载 作者:行者123 更新时间:2023-12-05 03:15:07 25 4
gpt4 key购买 nike

过去几个小时我一直在调试以下代码。我意识到这可能很愚蠢,但似乎无法弄清楚。

在第二个 for 循环中(参见 debug printfs),bitsA 的值发生了变化。我不明白为什么。

编辑:如果有人想知道 sat_count_update 中的代码是什么:

counter->taken = (bool)((1 << counter->cbits - 1) & counter->count) ;

文件:饱和计数器.H

#ifndef SATURATINGCOUNTER_H
#define SATURATINGCOUNTER_H
#include <stdbool.h>

//Macro function to return taken/not taken of counter
#define sat_count_taken(COUNTER) COUNTER->taken

typedef struct sat_count{
char count;
char cbits;
bool taken;
} sat_count_t;

//Initialize and return counter
void sat_count_init(char bits, sat_count_t *counter){

counter->count = 0;
counter->cbits = bits;
counter->taken = false;

}

//Update taken member of sat_counter_t based on count
void sat_count_update(sat_count_t *counter){
//COMMENTING OUT THIS LINE MAKES IT WORK. NORMALLY THERE IS CODE TO SET THE CORRECT VALUE
counter->taken = true;
}

//Up counter, respecting saturation
void sat_count_up(sat_count_t *counter){
//If counter is saturated
if ((counter->count < ( 1 << counter->cbits) - 1)) counter->count = counter->count + 1;
sat_count_update(counter);
}

//Down counter, respecting saturation
void sat_count_down(sat_count_t *counter){
//If counter is 0
if (counter->count > 0) --counter;
sat_count_update(counter);
}

#endif

饱和计数器测试.H

#include "SaturatingCounter.H"
#include "SaturatingCounter.H" //Multiple include to test include guards
#include <stdbool.h>
#include <stdio.h>

void main(){

//Initialize counter
char i,NULL1, NULL2, bitsA;
sat_count_t mycounter;

//Test all bit counters
for(bitsA=1;bitsA<=5;++bitsA){

sat_count_init(bitsA,&mycounter);
printf("***************************** %d bits **************\n",bitsA);
printf("**UP**\n");
for(i=0;i<((1<<bitsA) + 1);i++) {
printf("Counter is currently %d, %sTAKEN.\n",mycounter.count,(!mycounter.taken) ? "NOT " : "");
sat_count_up(&mycounter);
}


printf("**DOWN**\n");
for(i=0; i<(((1<<bitsA) + 1));i++) {
printf("Counter is currently %d, %sTAKEN.\n",mycounter.count,(!mycounter.taken) ? "NOT " : "");
//THIS IS WHERE bitsA CHANGES!
printf("DEBUG BEFORE: BITS: %d\n",bitsA);
// printf ("%p bitsA\n %p mycounter\n",&bitsA, &mycounter);
sat_count_down(&mycounter);
printf("DEBUG AFTER: BITS: %d\n",bitsA);
// printf ("%p bitsA\n %p mycounter\n",&bitsA, &mycounter);

}

}
}

最佳答案

你的问题在线

if (counter->count > 0) --counter;

您正在更改 counter 指向的位置 - 之前的内存位置是您存储 bitsA 的位置:

   char i,NULL1, NULL2, bitsA;
sat_count_t mycounter;

我想你是想减少其他东西 - 也许

if(count->count > 0) --(counter->count)

关于c - 函数调用后变量值发生变化,未被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20601939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com