Hello i am making a program in C which stores integers on a dynamic array which uses realloc every time it has to add a new element, i declare the array on the main:
int *abundants;
int count = abundant_numbers(&abundants);
once finished, i want to pass the modified array to another function to make other calculations
int abundant_numbers(int *abundants[]){
if (!(*abundants = (int*) malloc(sizeof(int)))){
perror("malloc error!\n");
exit(EXIT_FAILURE);
}
*abundants[0] = 12; //we know the very first abundant number
int count = 1, n = 14;
while (n < MAX_NUM){
if (is_abundant(n)) {
if (!(*abundants = (int*) realloc(*abundants,(count+1) * sizeof(int)))){
perror("Error in realloc\n");
exit(EXIT_FAILURE);
}
*abundants[count] = n;
count++;
}
n += 2; //no odd abundant numbers
}
return count;
}
the first time it enters on the if statement gives no problems, but the second time on the assignment i get a Segmentation Fault: 11, when accesing abundants[2], i dont understand why its not a valid position if it worked fine for abundants[1]
Thanks.
*abundants[count] = n;-->(*abundants)[count] = n;reallocin chunks, an often used strategy is to double the capacity once you run out (whether this is the best depends on your usecase).