I want to create a struct which encapsulates a dynamically allocated array. It looks like this:
typedef struct IntArray {
int *field;
size_t length;
} IntArray;
Then, I have a function which creates such an IntArray struct:
IntArray *createIntArray(size_t length) {
IntArray *output;
if ((output = malloc(sizeof(IntArray))) == NULL) {
return NULL;
}
output->field = calloc(length, sizeof(int));
output->length = length;
return output;
}
Here's the main:
int main() {
size_t size = 10;
IntArray *test = createIntArray(size);
for (int i = 0; i < size; i++) {
printf("%d\n", test[i]);
}
}
I expect calloc() to initialize the memory with zeros, however the output is strange:
I think these numbers are memory addresses, but where are they coming from? Every time I start the program, the numbers change but stay on the 1. and 6. positions..
Why is this happening?
EDIT:
I accidentally mixed up calloc and malloc here on stackoverflow, the problem actually occurs with the code above
You are trying to print a struct as an int
. A good compiler will warn you abut it if you turn on/up compiler warnings (-Wall
if you use gcc).
CreateIntArray creates a single IntArray
with field
of size length
.
If you want to print the allocated int
array you could use the following:
int main() {
size_t size = 10;
IntArray *test = createIntArray(size);
for (int i = 0; i < size; i++) {
printf("%d\n", test->field[i]);
}
}