简体   繁体   English

更改指针 (C) 时数组元素会发生什么变化?

[英]What happens to the array elements when changing the pointer (C)?

So I'm aware that this question is most likely asked before, but after near an hour of searching I decided to ask all the same.所以我知道这个问题很可能以前被问过,但经过近一个小时的搜索,我决定问同样的问题。 Pointing me to a dublicate question which has already been answered would really be appreciated.将我指向一个已经得到回答的重复问题将不胜感激。

Then, programming in basic C, I'm curious to what happens to the array-elements when changing its pointer to pointing something else?然后,在基本 C 中编程,我很好奇数组元素在将其指针更改为指向其他内容时会发生什么? Is it safe, without first freeing it?不首先释放它是否安全? For instance,例如,

int main()
{
    const int size = 3;
    int *p_arr = malloc(size * sizeof(int));

    for( int i=0; i<size; i++)
        p_arr[i] = i;

    int arr[size] = {0,0,0};

    p_arr = arr; // safe!?

    // What happens to the data previously allocated
    // and stored in *p_arr? Should one first call,
    // free(p_arr)
    // and then reallocate ..?
}

Essentially, changing the pointer will leave the data {0,1,2} in memory.本质上,更改指针会将数据 {0,1,2} 留在内存中。 Is this okay?这个可以吗?

Thanks alot for any help!非常感谢您的帮助!

Nothing happens to the data, except that it becomes unreachable ("leaked") and thus the memory is forever wasted, it can't be used for anything else until your program terminates (typically).数据没有任何变化,除了它变得无法访问(“泄漏”)并且因此内存永远被浪费了,它不能用于其他任何事情,直到您的程序终止(通常)。

Don't do this, it's very bad practice to leak memory.不要这样做,泄漏内存是非常糟糕的做法。

You should free() the memory when you no longer need it.当你不再需要它时,你应该free()内存。

Also, the allocation can be written:此外,分配可以写成:

p_arr = malloc(size * sizeof *p_arr);

to remove the duplication of the int type, and lock the size to the actual variable.删除int类型的重复,并将大小锁定到实际变量。 This is at least somewhat safer.这至少在某种程度上更安全​​。

数组{0,1,2}已经在内存中了,但是除非你再次指向数组头地址的指针,否则你无法得到它。

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

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