据我所知,当一个指针被传递给一个函数时,它只是一个真实指针的副本。现在,我想要更改真正的指针,而不必从函数返回指针。例如:
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);
最佳答案
我将尝试一次解决这些问题:
-
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);
-
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 的这个确切问题的链接.
-
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 .
-
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 中找到. -
int *a;
Is a the address of the memory containing the actual value, or the memory address of the pointer?
这个问题对我来说真的没有意义,但我会尽力解释。
a
(如果正确初始化 - 你的例子在这里不是)是一个地址(指针本身)。*a
是指向的对象 - 在本例中,它是一个int
。 -
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/