Storing Volatile Chars in an Array

637 Views Asked by At

Disclaimer: I'm quite new to C and to programming in general so this question may show a lack of basic knowledge.

I'm trying to store a set of temperature readings of type 'volatile char' in an array. The temperature reading and array are declared respectively as follows:

volatile char TempCelsiusDisplay[] = "+abc.d C";
volatile char temps[60];

The rest of the code appears to work fine, until I try to store a temperature value in the array

temps[59] = TempCelsiusDisplay;

Which throws up the error:

Error: A value of type "volatile char *" cannot be assigned to an entity of 
type "char" in "main.cpp", Line: 70, Col: 20

Is anybody able to explain why this is happening? It seems to me the way I have declared the array is not the correct way to declare a list of volatile chars, however I don't really understand what is happening or how to fix it.

Thanks in Advance :)

1

There are 1 best solutions below

0
Matthias Grün On

Temps is an array of single chars, so temps[59] is of type char. So by saying

temps[59] = TempCelsiusDisplay;

you are trying to assign a value of type char[] (char array) to a value of type char (single character), which of course is not possible.

If you want to copy the string in TempCelsiusDisplay into temps you could use strcpy_s:

strcpy_s((char*)temps, sizeof(temps), (const char*)TempCelsiusDisplay);

If, on the other hand, you want each of the entries in array temps to be able to hold a temperature string like the one contained in TempCelsiusDisplay, you would need to declare an array of strings (char pointers) like so:

volatile char* temps[60];

Then you could copy the string TempCelsiusDisplay into one of the strings in the array:

temps[0] = (char*) malloc(10);    // allocate memory (example: 10 bytes)
strcpy_s((char*)temps[0], 10, (const char*)TempCelsiusDisplay);
// ... use string
free((void*) temps[0]);    // free memory

Optionally, you could save yourself the trouble of dynamically allocating memory by declaring a multidimensional array, like so:

volatile char temps[60][10];

This declares 60 10-character arrays.

Then you can copy the string like before:

strcpy_s((char*)temps[0], sizeof(temps[0]), (const char*)TempCelsiusDisplay);