So I decided to write my own Big Integer library for a microcontoller in C (the PIC32 if that matters), but I'm having a weird problem that I don't understand. When the code is run, the big_int_t structs a and b are at different memory locations, but a->bytes and b->bytes appear to be at the same location (confirmed by printing their pointers). Setting a value in b->bytes also changes the value in a->bytes. In the main function below, printing the first element from either struct's bytes array shows 41. Am I doing something wrong?
#include <stdint.h>
#include <stdio.h>
typedef struct {
uint8_t size;
uint8_t *bytes;
} big_int_t;
void big_init(big_int_t *big, uint8_t size) {
big->size = size;
uint8_t bytes[size];
big->bytes = bytes;
uint8_t i;
for(i=0;i<big->size;i++) big->bytes[i] = 0;
}
int main() {
big_int_t a,b;
big_init(&a,1);
big_init(&b,1);
a.bytes[0] = 16;
b.bytes[0] = 41;
printf("%d\n",a.bytes[0]);
printf("%d\n",b.bytes[0]);
}
mallocto get memory forbytes. Do not use stack variable.