I am allocating memory as follows. Also trying to update it in another function.
int main() {
int* ptr = (int*)malloc(sizeof(int)*3);
ptr[0] = 0;
ptr[1] = 1;
ptr[2] = 2;
modifyArr(&ptr, 2);
}
void modifyArr(int** arr, int arrLen)
{
printf("Before modified\n");
printArray(*arr, arrLen);
for (int i = arrLen; i >= 0; i--)
{
*arr[i] = i; // here is error
}
printf("After modified\n");
printArray(*arr, arrLen);
}
So how can I modify this array inside another function?
In case my array would be fixed array as:
int arr[] = { 0,1,2 };
How can I update it in another function?
ptrto point to reallocated buffer). If you just want to change array contents, it's enough to pass the pointer value.*arr[i]doesn’t do what you want. Use(*arr)[i], probably.modifyArr(ptr, 2);and declaremodifyArr(int *arr, int arrLen)and writeprintArray(arr, arrLen),arr[i] = i, etc... You'd need to changeprintArraydeclaration/definition in that case as well.ptris already a pointer, you don't need to make a pointer to it, just pass it directly. Then you don't have to worry about the operator precedence.