在c中访问结构中的数组成员是访问值还是访问地址?
在以下代码中:在c中访问结构中的数组成员是访问值还是访问地址?,c,arrays,string,C,Arrays,String,在以下代码中: struct a { char name[18]; }customer; scanf("%s",customer.name); printf("%s",customer.name); struct a *pt=&customer; ` 由于将数组名指向该成员的第一个元素,customer.name是否指向该成员的第一个元素 在一本书中,有人写道,*(customer.name+2)等同于customer.name[2]和pt->name[2]。但我无法
struct a {
char name[18];
}customer;
scanf("%s",customer.name);
printf("%s",customer.name);
struct a *pt=&customer; `
由于将数组名指向该成员的第一个元素,customer.name
是否指向该成员的第一个元素
在一本书中,有人写道,
*(customer.name+2)
等同于customer.name[2]
和pt->name[2]
。但我无法理解这些注释,也无法理解为什么scanf()中的customer.name
函数是地址,而printf()中的函数不是地址?在这两种情况下,它都是地址。但是,其中一个使用该地址填充字符串,另一个使用该地址读取值
在printf
中,当您使用%s
时,函数需要该字符串的起始地址。您不应该被inti=10的情况所误解;printf(“%d”,i”);
哪个变量的值被传递给printf
。print函数中字符串的情况与您所看到的不同。在这种情况下在scanf
中,您最终传递了地址,因为数组衰减为指向第一个元素的指针。(某些情况下,这种衰减不会发生,如sizeof
,AlignOf
或操作符的地址&
等)。该指针包含数组第一个元素的地址
scanf("%s",customer.name);
^^^^
指向数组第一个元素的指针是char*
,它保存了scanf
将值写入所需内存地址所需的地址。为了澄清一点,您甚至可以等效地传递它:(前面的讨论解释了为什么可能)
在printf
中也它是一个正在以与以前相同的逻辑传递的地址,print
使用该地址来打印它所包含的字符,直到它到达\0
从frpintf
功能描述下:
如果不存在l
长度修饰符,参数应是指向
来自的字符类型为.280)个字符的数组的初始元素
数组写入(但不包括)终止null
字符。如果指定了精度,则不超过该数量的字节
如果未指定精度或大于
数组的大小,数组应包含空字符
作为一条经验法则-在scanf
的情况下,将始终传递用于存储输入数据的变量的地址。在printf
的情况下,它取决于使用的格式说明符-正如上面所示,%s
格式说明符需要一个地址,但%d
或%c
sspecifier没有。在这里的print()
和scanf()
示例中,customer.name
解析为指向数组name
的第一个元素的指针,该元素是customer
类型struct a
变量的成员
为了消除混淆,在使用%s
格式说明符和printf()
的情况下,所需的参数类型是指向数组的第一个元素的指针。因此,在使用printf()的情况下
call,参数customer.name
是正确的,它是一个指针。当数组用作函数参数时,它会衰减为指向其第一个元素的指针。在这两个函数scanf
和printf
中,参数customer.name
被转换为指针,并具有类型char*
<>customer.name
是指向name
字符数组中第一个字符的指针
customer.name
相当于&(customer.name[0])
customer.name
约定是访问结构中字符数组的典型方式
在printf()
%s
格式中,需要指向数组第一个元素的指针
结构a
、成员name
数组和name[0]
字符在内存中的地址完全相同。您可以在以下程序中看到:
#include <stdio.h>
#include <stdlib.h>
typedef struct a {
char name[18];
}customer;
int main()
{
customer bob;
customer *ptr;
scanf("%s",bob.name);
printf("Customer name is: %s\n",bob.name);
ptr = & bob;
printf("Memory Address of the bob structure is: %p\n", (void *) ptr);
printf("Memory Address of the 'bob.name' is: %p\n", (void *) &bob.name);
printf("Memory Address of the 'bob.name[0]' is: %p\n", (void *) &(bob.name[0]) );
return 0;
}
在某些情况下,数组表示为指针。
#include <stdio.h>
#include <stdlib.h>
typedef struct a {
char name[18];
}customer;
int main()
{
customer bob;
customer *ptr;
scanf("%s",bob.name);
printf("Customer name is: %s\n",bob.name);
ptr = & bob;
printf("Memory Address of the bob structure is: %p\n", (void *) ptr);
printf("Memory Address of the 'bob.name' is: %p\n", (void *) &bob.name);
printf("Memory Address of the 'bob.name[0]' is: %p\n", (void *) &(bob.name[0]) );
return 0;
}
Bob
Customer name is: Bob
Memory Address of the bob structure is: 0x7ffe0d7687e0
Memory Address of the 'bob.name' is: 0x7ffe0d7687e0
Memory Address of the 'bob.name[0]' is: 0x7ffe0d7687e0