Pardon_me
Pardon_me

Reputation: 735

changing value of variable in an array (C Programming)

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 which is a variable called selectChannel

so if the user is on channel 0, and they press R, i want temperatureSensor1Reading to be incremented. @icktoofay mentioned using pointers, I made their recommended changes but when I press r or f, no increase to temperature occurs.

enter code here
#include "stdafx.h" 
#include <Windows.h> //additional header added to allow for coloured text
#include "console.h"
#include <conio.h>
#include "lab4temperatureController.h"
#include <time.h>
//#define hConsole  
#define CH1 0
#define CH2 1
#define CH3 2

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


//Update Display:---------------------
//Description: prints out readings and updates with increment, decrement and average
//
//Parameters: lowlimit, highlimit, temperatures, Channels
//
//
//Returns:
//
//------------------------------------------------------------------
void updateDisplay()
{
        clrscr();
        HANDLE hConsole; //standard c library call 
        hConsole = GetStdHandle(STD_OUTPUT_HANDLE); //used for output screen buffer to allow for coloured text

    SetConsoleTextAttribute(hConsole, 2); //sets output screen colour for following text
    printf("\nCurrent Temperature for channel 1 is %d\n\n", temperatureSensor1Reading);
    printf("Upper Limit for channel 1 is  %d\n\n", getHighLimit(CH1));
    printf("Lower Limit for channel 1 is  %d\n\n", getLowLimit(CH1));
    setCurrentTemperature(CH1, temperatureSensor1Reading);

    SetConsoleTextAttribute(hConsole, 3); //sets output screen colour for following body of text
    printf("Current Temperature for channel 2 is  %d\n\n", temperatureSensor2Reading);
    printf("Upper Limit for channel 2 is  %d\n\n", getHighLimit(CH2));
    printf("Lower Limit for channel 2 is  %d\n\n", getLowLimit(CH2));
    setCurrentTemperature(CH2, temperatureSensor2Reading);

    SetConsoleTextAttribute(hConsole, 4); //sets output screen colour for following body of text
    printf("Current Temperature for channel 3 is %d\n\n", temperatureSensor3Reading);
    printf("Upper Limit for channel 3 is  %d\n\n", getHighLimit(CH3));
    printf("Lower Limit for channel 3 is  %d\n\n", getLowLimit(CH3));
    setCurrentTemperature(CH3, temperatureSensor3Reading);

    compareMinLimit(CH1);
    compareMinLimit(CH2);
    compareMinLimit(CH3);
    compareHighLimit(CH1);
    compareHighLimit(CH2);
    compareHighLimit(CH3);

    if (isAverageValid() == TRUE)
    {

        //if average is valid call function to calculate average and print returned value
        //SetConsoleTextAttribute(hConsole, 5); //sets output screen colour for following text
        printf("average for channel 1 is %d\n\n", calculateAverageTemperature(CH1));
        printf("average for channel 2 is %d\n\n", calculateAverageTemperature(CH2));
        printf("average for channel 3 is %d\n\n", calculateAverageTemperature(CH3));
        //--if average is valid call functions to determine min and max values and print returned values for each channel
        temperature_t max1 = calculateMax(CH1); 
        temperature_t min1 = calculateMin(CH1);
        temperature_t max2 = calculateMax(CH2);
        temperature_t min2 = calculateMin(CH2);
        temperature_t max3 = calculateMax(CH3);
        temperature_t min3 = calculateMin(CH3);
        printf("the maximum temperature is: %d \n \nthe minimum temperature is: %d \n \n", max1,min1); //display each channels max/min
        printf("the maximum temperature is: %d \n \nthe minimum temperature is: %d \n \n ", max2,min2);
        printf("the maximum temperature is: %d \n \nthe minimum temperature is: %d \n \n", max3,min3);
        // if average is valid call function to print histogram

        SetConsoleTextAttribute(hConsole, 15);
        printf("the following is the pressure histogram for channel %d \n \n", selectChannel+1); 

            printPressureHistogram(selectChannel);


            //print out the current channels histograms
        //initializeTemperatureSubsystem();
    }
}

//main:---------------------
//Description: initializes the temperature subsystem and provides user with various input commands
// which can be used to increment, decrement and get average value of temperatures
//Parameters: lowlimit, highlimit, temperatures, MAXSAMPLES
//
//Returns:
//------------------------------------------------------------------

int _tmain(int argc, _TCHAR* argv[])
{
    // -- insert variable declaration for time ------
time_t timeOfLastStoredSample, currentTime;
//==============================================

initializeTemperatureSubsystem();

//--insert code to store the initial sensor temperature------
recordCurrentTemperature(CH1, temperatureSensor1Reading); //records each channels temperature reading
recordCurrentTemperature(CH2, temperatureSensor2Reading);
recordCurrentTemperature(CH3, temperatureSensor3Reading);

//--record the time as timeOfLastSample
timeOfLastStoredSample = time(NULL);

//==========================================

printf("\n Q,A: Adjust the current temperature select, W,S adjust our limit, E,D adjust lower limit \n");
unsigned char quit = 'n'; //binds quit to literal value of 'n'
while(quit == 'n') //executes until user quits
{

//-- insert code to get currentTime----
    time(&currentTime); //ASK ABOUT THIS (we haev to explicitly direct time to the address for current time

//--insert code to compare the two time values and see if 20 seconds have elapse
    if (currentTime - timeOfLastStoredSample >= 1)
    {   
        //if 20 seconds have elapsed, record the time and update value held by timeLastStoredSample
        recordCurrentTemperature(CH1, temperatureSensor1Reading);
        recordCurrentTemperature(CH2, temperatureSensor2Reading);
        recordCurrentTemperature(CH3, temperatureSensor3Reading);

        time(&timeOfLastStoredSample);

    }


    updateDisplay();
    Sleep(200);
    unsigned char selectedCommand = 0;

    if( _kbhit()  )
        {
        selectedCommand = _getch();

        switch(selectedCommand)
            {

            case 'Q': //if user input is Q
            case 'q'://if user input is q
            selectChannel ++;
            if (selectChannel > 2) //determine which channel the user is on, if greater than 2, then cycle to channel 0
                selectChannel = CH1; 
                printf ("\n your current channel is %d \n \n ", selectChannel + 1); 

                break; //exits loop

            case 'A': //if user input is A
            case 'a'://if user input is a
            selectChannel --;
            if (selectChannel < 0) //determine which channel the user is on, if less than 0, then cycle to channel 2
                selectChannel = CH3; 
                printf (" \n your current channel is %d \n \n", selectChannel + 1);

                break; //exits loop

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

            *temperatureSensorReadings[selectChannel]++;

                break; //exits loop

            case 'F': //if user input is 'F'
            case 'f': //if user input is 'f'        

            *temperatureSensorReadings[selectChannel]--;

                break; //exits loop

            case 'W': //if user input is 'W'
            case 'w': //if user input is 'w'

            increaseHighLimit(selectChannel); //increase CH1 high limit

                break; //exits loop

            case 'S':
            case 's'://if user input is 'S

            decreaseHighLimit(selectChannel); //decrement CH1 high limit

            break; //exits loop

            case 'E':
            case 'e': //if user input is E

                increaseLowLimit(selectChannel); //decrement CH1 low limit

                break; //exits loop

            case'D':
            case'd': //if user input is D


                decreaseLowLimit(selectChannel); //decrement CH1 lowlimit

                break;//exits loop



            case'X': //conditions apply for preceding case as well (for upper and lowercase "q")
                clrscr(); //executes function
                gotoxy(2,2); //returns command line to 2,2 location
                printf("Exiting...Bye!\n");
                quit = 'y'; //cause exit of while loop
                break;

            default:
                clrscr(); //executes function
                gotoxy(1,1); //takes command line to location 1,1
                printf("Q,A: Adjust the current temperature select, W,S adjust our limit, E,D adjust lower limit \n");
                break;
        }//eo of switch
    }//eo kbhit()
}// eo while loop
return 0;

}

Upvotes: 0

Views: 1574

Answers (1)

user1944441
user1944441

Reputation:

The problem is in temperature_t *temperatureSensorReadings[3] which is declared in a very weird way.

When you increase ( or decrease ) temperature with *temperatureSensorReadings[selectChannel]++; you arent increasing the value of the temperature stored in array but a pointer to that value. Pointer then points to unallocated space causing undefined behaviour.

Using proper parentheses will solve that

( *temperatureSensorReadings[selectChannel] )++;



A proper solution would be declaring array as:

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

and changing lines that increases the values to a much simpler code

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

temperatureSensorReadings[selectChannel]++;

This of course means changing all the other code that might rely on this array.

Upvotes: 2

Related Questions