0

I set up a structure which among other things contains an array of 8 bit unsigned integers. At compile time the size of this array is unknown - so I thought I turn it into a pointer and create the array later. Here's a simplified example:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

struct value {
    uint8_t *data;
};

struct value values[10];

void fillIt(int whichOne)
{
    uint8_t tempArray[2];
    switch(whichOne)
    {
    case 0:
        tempArray[0]=10;
        tempArray[1]=20;
        break;
    case 1:
        tempArray[0]=30;
        tempArray[1]=40;
        break;
    default:
        break;
    }
    values[whichOne].data=tempArray;   
}

int main(void)
{
    fillIt(0);

    printf("values[0]  %u %u\n",values[0].data[0],values[0].data[1]);

    fillIt(1);
    printf("values[0]  %u %u\n",values[0].data[0],values[0].data[1]);
    printf("values[1]  %u %u\n",values[1].data[0],values[1].data[1]);

    return 0;
}

This will output the following

values[0]  10 20
values[0]  30 40
values[1]  30 40

So the second time I call fillIt(), values[0].data contains the same data as values[1].data because both are pointing to the same temporary array, I guess. How can I create 'individual' arrays I could point to?

user4581301
  • 33,082
  • 7
  • 33
  • 54
obscure
  • 11,916
  • 2
  • 17
  • 36
  • `values[whichOne].data=tempArray;` creates a dangling pointer – Richard Critten Oct 03 '17 at 21:10
  • The `tempArray` is vanishing to a non-existence right after the `fillIt` function is returned and only `values[whichOne].data` knows where its grave is.... – Eugene Sh. Oct 03 '17 at 21:10
  • `tempArray` is just as the name implies: temporary. Once it goes out of scope, it ceases to exist and anything that is pointing at it is pointing to garbage. You need to either dynamically allocate memory with `malloc`, or you need to declare the array somewhere that it will remain in scope for the duration of its use. – Christian Gibbons Oct 03 '17 at 21:13

0 Answers0