If I have a void pointer, how do I put an int into it?

前端 未结 5 1811
情歌与酒
情歌与酒 2021-02-04 09:47

I have an array of arbitrary values, so I have defined it as an array of void pointers, so I can point to any kind of information (like int, character arrays, etc).

相关标签:
5条回答
  • 2021-02-04 10:02
    *((int*)data[0])=x;
    

    will do it.

    You might want to consider using a union. Something like this:

    union myvalues
    {
        int i;
        double d;
        long l;
    };
    

    You could then have

    union myvalues *foo[10];
    foo[0] = malloc(sizeof(union myvalues));
    foo[0]->i = x;
    

    You can also typedef the union. sizeof(union myvalues) will be the maximum of sizeof the members. So if you have int i; and char c[40] in the union, sizeof(union myvalues) will be 40. Writing to i will then overwrite the first 4 characters in c (assuming your ints are 4 bytes).

    0 讨论(0)
  • 2021-02-04 10:02

    for aliasing reasons its far better to do

    mempcy( data[0], &x, sizeof( int ) );
    

    As it happens the compiler will optimise the memcpy call out as sizeof( int ) is a constant value but it won't break various aliasing rules.

    0 讨论(0)
  • 2021-02-04 10:10

    try this:

    data[0] = malloc(sizeof(int));
    *((int*)data[0]) = x;
    

    or

    (int) (*(data[0])) = x;
    

    don't forget to

    free (data[0]);
    

    afterwards.

    0 讨论(0)
  • 2021-02-04 10:17
    *((int *)data[0]) = x;
    

    A copy of x will be made, so the fact it is a local variable is not important.

    0 讨论(0)
  • 2021-02-04 10:22

    Although you can use a cast to make the assignment, it is probably much cleaner to write the code like:

    void *data[ 10 ];
    int x = 100;
    int *p;
    
    p = malloc( sizeof *p );
    data[ 0 ] = p;
    *p = x;
    
    0 讨论(0)
提交回复
热议问题