简体   繁体   中英

Dynamic memory allocation and passing in function

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?

The array subscript operator [] has higher precedence than the pointer dereference operator * . See the order of precedence of operators in C . As a result, this:

*arr[i] = i;

Really means:

*(arr[i]) = i;

Which means you're treating arr as an array of pointers instead of a pointer to an array. As a result, you end up writing to the wrong place and invoke undefined behavior .

You need to put parenthesis around *arr to get what you want:

(*arr)[i] = i;

However, since you're only updating the memory the pointer points to and not actually modifying the pointer, there's no need to pass the pointer's address. Just pass it in directly:

void modifyArr(int* arr, int arrLen)
{
    printf("Before modified\n");
    printArray(arr, arrLen);
    for (int i = arrLen;  i >= 0; i--)
    {
        arr[i] = i;
    }
    printf("After modified\n");
    printArray(arr, arrLen);
}

And call it like this:

modifyArr(ptr, 2);

You probably also want to modify printArray to do the same.

The things with pointers are pretty simple when you remember two things - what you want to get and how do you get it?

Here you want to get the consecutive elements memory of which you have allocated. And how do you get it? Yes you are so right using [] and * but then again there is one thing known as precedence. Precedence of [] is higher than * . So you wrote this *(arr[i]) where as you want (*arr)[i] . First get the pointer then get the elements using [] on it.

Here you have achieved what is known as undefined behavior . Because you have accessed something which is not allocated by you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM