简体   繁体   中英

how do I increment the value of a variable in an array (C programming)

I have been fiddling with my code for the last hour or so but i can't seem to get it working the way that I want to. I have been reading about the idea of arrays being fixed states, but to be honest I'm just burnt out from this little experiment and would really appreciate some help.

basically what I want to do is to take my three temperature sensor readings that i have declared and lump them into an array. from that point I want to be able to increment the value of each respective variable in the array, depending on what current channel the user has selected.

so if the user is on channel 0, and they press R, i want temperatureSensor1Reading to be incremented with the following block of code. Please ignore the incompleteness I know this is not the entire code, but this isolates my issue at the moment.

temperature_t is a typedef that i declared earlier. The program does not give me any errors but it does not do anything when i press R or F (increment or decrement). I've just highlighted the blocks of code that reflect my goals. Thanks for your help in advance!

temperature_t selectChannel = 0;
temperature_t temperatureSensor1Reading = 75;
temperature_t temperatureSensor2Reading = 75;
temperature_t temperatureSensor3Reading = 75;
temperature_t temperatureSensorReadings[3] = {temperatureSensor1Reading, temperatureSensor2Reading, temperatureSensor3Reading};


case 'R': //if user input is R
case 'r'://if user input is r


    temperatureSensorReadings[selectChannel] ++;

break; //exits loop

Your array just contains copies of the values of the variables at the time of the creation of the array. When you change the array, you are changing just that, and not the variables from which the values were copied. You can achieve what you're trying to do by making the array hold not temperatures, but pointers to temperatures:

temperature_t *readings[] = {&temp1, &temp2, &temp3};
// ...later...
(*readings[channel])++;

You are fixed by 'pass by value' and 'pass by reference' here. @icktoofay 's answer is right. He replaces your 'pass by value' by 'pass by reference'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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