Search code examples
c++multithreadingarraysmallocvolatile

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.


Solution

  • 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?