简体   繁体   English

动态内存分配和传入功能

[英]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 . 请参阅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. 这意味着您将arr视为指针数组,而不是指向数组的指针。 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周围加上括号以获取所需的内容:

(*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. 您可能还希望修改printArray以执行相同的操作。

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] . 因此,您在需要的地方(*arr)[i]写下了这个*(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. 因为您访问的内容不是您分配的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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