Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare an array created using malloc to be volatile in c++

I presume that the following will give me 10 volatile ints

volatile int foo[10];

However, I don't think the following will do the same thing.

volatile int* foo;
foo = malloc(sizeof(int)*10);

Please correct me if I am wrong about this and how I can have a volatile array of items using malloc.

Thanks.

like image 680
Mark Avatar asked Feb 21 '10 04:02

Mark


2 Answers

int volatile * foo;

read from right to left "foo is a pointer to a volatile int"

so whatever int you access through foo, the int will be volatile.

P.S.

int * volatile foo; // "foo is a volatile pointer to an int"

!=

volatile int * foo; // foo is a pointer to an int, volatile

Meaning foo is volatile. The second case is really just a leftover of the general right-to-left rule. The lesson to be learned is get in the habit of using

char const * foo;

instead of the more common

const char * foo;

If you want more complicated things like "pointer to function returning pointer to int" to make any sense.

P.S., and this is a biggy (and the main reason I'm adding an answer):

I note that you included "multithreading" as a tag. Do you realize that volatile does little/nothing of good with respect to multithreading?

like image 199
tony Avatar answered Oct 14 '22 03:10

tony


volatile int* foo;

is the way to go. The volatile type qualifier works just like the const type qualifier. If you wanted a pointer to a constant array of integer you would write:

const int* foo;

whereas

int* const foo;

is a constant pointer to an integer that can itself be changed. volatile works the same way.

like image 22
MtnViewJohn Avatar answered Oct 14 '22 04:10

MtnViewJohn