Reputation: 1624
I have the following code:
#include <stdio.h>
#include <stdlib.h>
struct sArray {
int *arr;
int index; // ultimo indice riempito
int prev_index; // penultimo indice
int lenght;
};
typedef struct sArray arr; // structArray with type arr
void init(arr *a, int initSize) {
a->arr = malloc(initSize * sizeof(int));
a->lenght = initSize;
a->index = 0;
a->prev_index = 0;
}
void insert(arr *a, int value) {
int index = a->index;
int length = a->lenght;
int prev_index = a->prev_index;
if (index < length) {
a->arr[index] = value;
} else {
a->arr = malloc(1 * sizeof(int));
a->arr[index] = value;
a->lenght += 1;
}
a->index += 1;
if (index > 0){
a->prev_index += 1;
};
}
int main(void) {
arr a;
// init array with 10 elements
init(&a, 10);
// try to add 20 elements
for (int i = 0; i < 20; i++) {
insert(&a, i);
printf("Valore: %d\n", a.arr[i]);
}
printf("Lenght a: %d\n", a.lenght);
// the left operand of -> must be a pointer;
// the . operator is used if it is not a pointer
for (int i = 0; i < 20; i++) { // PROBLEM HERE
printf("Valore: %d\n", a.arr[i]);
}
return 0;
}
I don't understand why I can't print the array's elements (a.arr[i]
) inside the second for loop in main
function. In particular, the elements are correctly printed inside the first loop in which there is a insert()
function, but in the second loop the elements are printed totally random, while I expect that the elements should be from 0
to 19
.
Upvotes: 0
Views: 35
Reputation: 75062
Your allocation in insert()
is wrong.
a->arr = malloc(1 * sizeof(int));
allocate a buffer for only one new element.
Instead of this, you have to
a->lenght + 1
int
s)You can do this via realloc()
like this:
a->arr = realloc(a->arr, (a->lenght + 1) * sizeof(int));
Upvotes: 2