使用 海湾合作委员会 4.4.3 c89:
我正在处理以下代码:
我只是有一些关于取消引用 src 指针的问题。在调用函数中声明为:
char src[] = "device_id";
我的困惑在于取消引用 src:
for(i = 0; src[i] != '\0'; i++) {
printf("src %d: [ %s ]\n", i, &src[i]);
}
src
已退化为指针。因此 src 将指向数组中的第一个元素,即字符 d:
src -> "device_id"
因此,当我执行此操作时,我将取消引用该值,以便它将返回当前指向的字符。对于这个例子,当它到达 nul 时,它将从 for 循环中中断。
For example i = 0
对于 &src[i]
我得到的是字符的地址而不是字符本身?
因此,src[i]
将取消引用并返回 d,&src[i]
将返回 d 的地址。
因为 *dest[]
是一个 char 指针数组,所以它需要一个地址。所以在这里我将字符的地址分配给指向 char 的指针数组。
dest[i] = &src[i];
使用 &src[i]
或 src[i]
在 printf 函数中为 %s 执行此操作有什么区别:
printf("src %d: [ %s ]\n", i, &src[i]);
或
printf("src %d: [ %s ]\n", i, src[i]);
源代码:
void inc_array(char *src, size_t size)
{
/* Array of pointers */
char *dest[size];
size_t i = 0;
memset(dest, 0, size * (sizeof char*));
/* Display contents of src */
for(i = 0; src[i] != '\0'; i++) {
printf("src %d: [ %s ]\n", i, &src[i]);
}
/* copy contents to dest */
for(i = 0; i < 9; i++) {
dest[i] = &src[i];
}
/* Display the contest of dest */
for(i = 0; *dest[i] != '\0'; i++) {
printf("dest %d: [ %s ]\n", i, dest[i]);
}
}
非常感谢您的建议,
最佳答案
For
&src[i]
am I getting the address of the character instead of the character itself? So wheresrc[i]
will dereference and returnd
,&src[i]
will return the address of d.
src[i]
相当于 *(src + i)
,因此 &src[i]
与 相同&*(src + i)
,可以简化为src + i
。它只是执行指针算术并且不会发生取消引用。
src[i]
为您提供 src
中索引 i
处的字符,以及 &src[i]
为您提供指向 src
中第 i
个字符的指针。
关于c - 取消引用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3527850/