I have been blocking for a while now on a function whose purpose is to assign a value to the respective cells of the sent pointed array:
void assign(T** pointerArray, U linkedListOfValues) {
size_t i = 0;
while (linkedListOfValues != NULL) {
*pointerArray[i++] = convert(linkedListOfValues->current); // Crash here, when add a second (or more) item
linkedListOfValues = linkedListOfValues->next;
}
}
As commented in the code, when I add more than one element to this pointed array, the program stops. There is no error message or warning. I use this function as such:
T* array = malloc(size * sizeof(T));
assign(&array, myLinkedList);
size represents the number of elements present in the linked list, and returns a correct value; the types used (U and T) are very arbitrary, and the convert function converts an element of type U into an element of type T.
The tests I performed did not find any errors in the convert function and in the dynamic allocation.
When I try without using this function, the program works correctly:
T* array = malloc(size * sizeof(T));
size_t i = 0;
while (linkedListOfValues != NULL) {
array[i++] = convert(linkedListOfValues->current);
linkedListOfValues = linkedListOfValues->next;
}
I don't understand what makes my function crash, since I only make a reference, using pointers, to the initial array. What's my mistake?
Ps: I started the C again a little while ago, maybe the solution is obvious, excuse me if that's the case.
T* array = malloc(size * sizeof(T));<<-- is not an array of pointers.convertactually returns typeT, and not a pointer to something, then all you need to do is remove a couple of*and a&. See minimal reproducible example.T* pointerArrayas first argument and usepointerArray[i++](excluding *) to assign values to. You do not need double pointer if you do not need to reassign new array or change its base pointer.