【发布时间】:2010-08-20 02:49:36
【问题描述】:
使用 gcc 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"
所以当我这样做src[i] 时,我正在取消引用该值,因此它将返回当前指向的字符。对于这个例子,当它到达 nul 时,它将从 for 循环中中断。
For example i = 0
对于&src[i],我得到的是角色的地址而不是角色本身吗?
所以src[i]会在哪里解引用并返回d,&src[i]会返回d的地址。
因为*dest[] 是一个字符指针数组,所以它需要一个地址。所以在这里我将字符的地址分配给指向 char 的指针数组。
dest[i] = &src[i];
使用&src[i] 或src[i] 在 %s 的 printf 函数中执行此操作是否有区别:
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]);
}
}
非常感谢您的任何建议,
【问题讨论】: