我前段时间问过一个我不记得如何操作基本指针的帐户,有人给了我一个非常好的演示
例如
char *ptr = "hello" (hello = a char array)
所以现在 *ptr
指向 'h'
ptr++
意味着移动 ptr
指向下一个元素,为了获得它的值,我执行 *ptr
并且这给了我 e
到目前为止一切正常,我希望 :D,但现在我需要操作一个 char **ptr
并且想知道我如何以模仿二维数组效果的方式做到这一点?
一些基本技巧将不胜感激,因为我需要做一个具有 **ptr
的作业来模仿二维数组,并且不知道它是如何做到的,这意味着我什至无法解决它在纸上(例如,如何取消引用 **ptr
,如何获取 [x][y]
值等)
谢谢
最佳答案
如果所有地址都已正确设置,您可以像为数组下标一样为指针下标。
假设如下声明:
char **ptr;
这里是各种表达式的类型:
Expression Type Equivalent expressions (yield same value) ---------- ---- ----------------------------------------- ptr char ** &ptr[0] *ptr char * ptr[0] *(ptr+i) char * ptr[i]; &ptr[i][0] **ptr char ptr[0][0] *(*(ptr+i)) char ptr[i][0]; *ptr[i] *(*(ptr+i)+j) char ptr[i][j]
thus:
ptr
can be treated as though it was an array of strings (2-d array of char)ptr[i]
points to the beginning of the i'th string in the listptr[i][j]
is the value of the j'th character of the i'th string in the list- The expressions
ptr++
and++ptr
will advanceptr
to point to the next string - The expressions
(*ptr)++
and++(*ptr)
will advance*ptr
to point to the next character
As for setting up your pointers, this arrangement assumes everything has already been allocated as static arrays or dynamically through malloc
. You cannot just write
char **ptr = {"foo", "bar", "bletch"}; // using aggregate initializer on
// non-aggregate type; bad juju,
// a.k.a undefined behavior
或
char **ptr; // ptr has not been initialized to point anywhere
ptr[0] = "foo"; // dereferencing ptr via subscript invokes undefined
ptr[1] = "bar"; // behavior
ptr[2] = "bletch";
通常,当您像使用数组一样使用指针时,您将使用 malloc
或类似的东西来分配缓冲区:
char **ptr = malloc(sizeof *ptr * N);
if (ptr)
{
ptr[0] = "foo"; // ptr[i] gets address of
ptr[1] = "bar"; // string literal
ptr[2] = "bletch";
...
}
或
char **ptr = malloc(sizeof *ptr * N);
if (ptr)
{
size_t i;
for (i = 0; i < N; i++)
{
ptr[i] = malloc(sizeof *ptr[i] * M); // strictly speaking, the sizeof
if (ptr[i]) // is not necessary here
{
//initialize ptr[i]
}
}
}
关于c - 指针所需的基本帮助(双重间接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2445848/