c - 存储指针值

标签 c pointers memory-management

据我所知,当一个指针被传递给一个函数时,它只是一个真实指针的副本。现在,我想要更改真正的指针,而不必从函数返回指针。例如:

int *ptr;

void allocateMemory(int *pointer)
{
     pointer = malloc(sizeof(int));
}

allocateMemory(ptr);

另一件事,即如何为二维或更多维数组分配内存?不是通过下标,而是通过指针运算。这是:

int array[2][3];
array[2][1] = 10;

等同于:

int **array;
*(*(array+2)+1) = 10

另外,为什么我必须传入函数指针的内存地址,而不是实际的指针本身。例如:

整数 *a;

为什么不:

allocateMemory(*a) 

但是

allocateMemory(a)

我知道我总是必须这样做,但我真的不明白为什么。请向我解释。

最后一件事是,在这样的指针中:

int *a;

a是包含​​实际值的内存地址,还是指针的内存地址?我一直认为a是它指向的实际值的内存地址,但我不确定这一点。顺便说一下,打印这样的指针时:

printf("Is this address of integer it is pointing to?%p\n",a);
printf("Is this address of the pointer itself?%p\n",&a);

最佳答案

我将尝试一次解决这些问题:

  1. Now, I want the real pointer to be changed without having to return a pointer from a function.

    您需要使用更多的间接层:

    int *ptr;
    
    void allocateMemory(int **pointer)
    {
        *pointer = malloc(sizeof(int));
    }
    
    allocateMemory(&ptr);
    

    Here is a good explanation来自 comp.lang.c FAQ .

  2. Another thing, which is, how can I allocate memory to 2 or more dimensional arrays?

    第一个维度的一个分配,然后另一个维度的分配循环:

    int **x = malloc(sizeof(int *) * 2);
    for (i = 0; i < 2; i++)
        x[i] = malloc(sizeof(int) * 3);
    

    再次,here是来自 comp.lang.c FAQ 的这个确切问题的链接.

  3. Is this:

    int array[2][3];
    array[2][1] = 10;
    

    the same as:

    int **array;
    *(*(array+2)+1) = 10
    

    绝对不是。指针和数组是不同的。不过,您有时可以互换使用它们。查看these questions来自 comp.lang.c FAQ .

  4. Also, why do I have to pass in the memory address of a pointer to a function, not the actual pointer itself?

    why not:

    allocateMemory(*a) 
    

    这是两件事 - C 没有传递引用,除非你通过传递指针自己实现它,在这种情况下也是因为 a 还没有初始化 - 如果你取消引用它,你会导致未定义的行为。此问题与 this one 类似。 , 在 comp.lang.c FAQ 中找到.

  5. int *a;
    

    Is a the address of the memory containing the actual value, or the memory address of the pointer?

    这个问题对我来说真的没有意义,但我会尽力解释。 a (如果正确初始化 - 你的例子在这里不是)是一个地址(指针本身)。 *a 是指向的对象 - 在本例中,它是一个 int

  6. By the way, when printing such pointer like this:

    printf("Is this address of integer it is pointing to?%p\n",a);
    printf("Is this address of the pointer itself?%p\n",&a);
    

    两种情况都是正确的。

关于c - 存储指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4660321/

相关文章:

c - 我在 x 中出现了多少次(无符号 32 位整数 C)

c - 当信号到达时线程是否继续执行?

c - C中数组指针的问题

ios App 在解除分配 UIView 子类实例时崩溃

c++ - 如何在 C++ 中处理可变大小的小对象的分配/释放

c - 识别 C 上的线程

c - 为什么增量运算符会修改原始值而位运算符不会?

c - 在C中访问链表的第一个节点

c - x86 汇编代码中的指针引用

c++ - C++中static的含义