I have this struct:
(struct.h)
#pragma once
#ifndef STRUCT_H
#define STRUCT_H
typedef struct {
unsigned int id;
char *name;
char *address;
} Struct;
#endif
I made a dynamic array containing these structs. I also have a loop that puts some data in those structs:
(main.c)
#include <stdio.h>
#include <stdlib.h>
#include "struct.h"
int main() {
int nStructs = 3;
Struct *structArray = calloc(nStructs, sizeof * structArray);
char input[30];
for (int i = 0; i < nStructs; i++) {
structArray[i].id = i;
sprintf(input, "name_%d", i);
structArray[i].name = input;
sprintf(input, "addr_%d", i);
structArray[i].address = input;
}
for (int i = 0; i < nStructs; i++) {
printf("\n[%04d] ID: %d\n", structArray[i].id, structArray[i].id);
printf("[%04d] NAME: %s\n", structArray[i].id, structArray[i].name);
printf("[%04d] ADDR: %s\n", structArray[i].id, structArray[i].address);
}
free(structArray);
return 0;
}
When I try to run this code, the 'int ID' is printed the right way, but the 'char *name' and 'char *address' are all containing the last value from the loop (in this case "addr_3"):
(output)
[0000] ID: 0
[0000] NAME: addr_2
[0000] ADDR: addr_2
[0001] ID: 1
[0001] NAME: addr_2
[0001] ADDR: addr_2
[0002] ID: 2
[0002] NAME: addr_2
[0002] ADDR: addr_2
I tried to use the debugger in visual studio and it looks like the values are ok when they are put in the array (first for loop), but that they get overwritten at some point. Since im new to visual studio, I don't know how to see the values of the array at a specific point and not just at the value [i].
What am i doing wrong here?
EDIT: I copy/pasted this code from my main project so only the part that im testing will be in the question. But I see I forgot to add 'free(structArray);' above 'return 0;'. Its added in the question now so others don't make the same mistake.